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/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/pwmc_3pwm.c
/** ****************************************************************************** * @file pwmc_3pwm.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides the firmware functions that implement 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 */ /* Includes ------------------------------------------------------------------*/ #include "pwmc_3pwm.h" #include "pwm_common_sixstep.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk_6s * @{ */ /** * @defgroup pwmc_3pwm Six-Step, 3 signals PWM generation * * @brief PWM generation implementation for Six-Step drive with 3 PWM duty cycles * * This implementation only drives the high sides of the bridges. The low sides are * automatically driven by the gate driver that inserts the dead time. * * Three additional signals are generated to enable or disable the PWM output of each * phase. * * @todo: Complete documentation. * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH3) /* Private function prototypes -----------------------------------------------*/ void ThreePwm_ResetEnablePins( PWMC_ThreePwm_Handle_t * pHandle ); /** * @brief It initializes TIMx and NVIC * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void ThreePwm_Init( PWMC_ThreePwm_Handle_t * pHandle ) { if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* Enable the CCS */ LL_RCC_HSE_EnableCSS(); /* Peripheral clocks enabling END ----------------------------------------*/ /* Clear TIMx break flag. */ LL_TIM_ClearFlag_BRK( pHandle->pParams_str->TIMx ); LL_TIM_EnableIT_BRK( pHandle->pParams_str->TIMx ); LL_TIM_ClearFlag_UPDATE( pHandle->pParams_str->TIMx ); /* disable ADC source trigger */ LL_TIM_SetTriggerOutput(pHandle->pParams_str->TIMx, LL_TIM_TRGO_RESET); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( pHandle->pParams_str->TIMx, TIMxCCER_MASK_CH123 ); /* Clear the flags */ pHandle->_Super.OverVoltageFlag = false; pHandle->_Super.OverCurrentFlag = false; pHandle->_Super.driverProtectionFlag = false; pHandle->FastDemagUpdated = true; pHandle->_Super.hElAngle = 0; LL_TIM_EnableCounter( pHandle->pParams_str->TIMx ); if (pHandle->pParams_str->OCPolarity == LL_TIM_OCPOLARITY_HIGH) { pHandle->NegOCPolarity = LL_TIM_OCPOLARITY_LOW; } else { pHandle->NegOCPolarity = LL_TIM_OCPOLARITY_HIGH; } } } /** * @brief It updates the stored duty cycle variable. * @param pHandle Pointer on the target component instance. * @param new duty cycle value. * @retval none */ __weak void PWMC_SetPhaseVoltage( PWMC_Handle_t * pHandle, uint16_t DutyCycle ) { pHandle->CntPh = DutyCycle; } /** * @brief It writes the duty cycle into timer shadow registers. * @param pHandle Pointer on the target component instance. * @retval none */ __weak void ThreePwm_LoadNextStep( PWMC_ThreePwm_Handle_t * pHandle, int16_t Direction ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.NextStep = PWMC_ElAngleToStep(&(pHandle->_Super)); if (pHandle->_Super.Step != pHandle->_Super.NextStep) { pHandle->DemagCounter = 0; if (pHandle->_Super.ModUpdateReq == ENABLE_FAST_DEMAG) { pHandle->FastDemag = true; pHandle->_Super.ModUpdateReq = NO_REQUEST; } if (pHandle->_Super.ModUpdateReq == DISABLE_FAST_DEMAG) { ThreePwm_ResetOCPolarity(pHandle); LL_TIM_GenerateEvent_COM( TIMx ); pHandle->FastDemag = false; pHandle->_Super.ModUpdateReq = NO_REQUEST; } } /* Fast demagnetization */ if (( pHandle->FastDemag == true ) && ( pHandle->DemagCounter < (pHandle->_Super.DemagCounterThreshold))) { uint16_t CWFastDemagPulse, CCWFastDemagPulse; uint32_t CWFastDemagPolarity, CCWFastDemagPolarity; pHandle->FastDemagUpdated = false; if (Direction > 0) { CWFastDemagPulse = pHandle->_Super.CntPh; CCWFastDemagPulse = 0; CWFastDemagPolarity = pHandle->NegOCPolarity; CCWFastDemagPolarity = pHandle->pParams_str->OCPolarity; } else { CWFastDemagPulse = 0; CCWFastDemagPulse = pHandle->_Super.CntPh; CWFastDemagPolarity = pHandle->pParams_str->OCPolarity; CCWFastDemagPolarity = pHandle->NegOCPolarity; } switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CWFastDemagPolarity); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CCWFastDemagPolarity); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CWFastDemagPolarity); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CCWFastDemagPolarity); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CWFastDemagPolarity); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CCWFastDemagPolarity); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; } } /* Alignment between two adjacent steps, CW direction*/ else if ( pHandle->_Super.AlignFlag == 1 ) { switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; } } /* Alignment between two adjacent steps, CCW direction*/ else if ( pHandle->_Super.AlignFlag == -1 ) { switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; } } /* standard configuration */ else { if (pHandle->DemagCounter >= pHandle->_Super.DemagCounterThreshold ) { pHandle->FastDemagUpdated = true; ThreePwm_ResetOCPolarity(pHandle); LL_TIM_GenerateEvent_COM( TIMx ); } switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } break; } } } /** * @brief It uploads the values into registers. * @param pHandle Pointer on the target component instance. * @retval bool Registers have been updated */ __weak bool ThreePwm_ApplyNextStep( PWMC_ThreePwm_Handle_t * pHandle ) { bool retVal = false; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if (pHandle->_Super.Step != pHandle->_Super.NextStep) { LL_TIM_GenerateEvent_COM( TIMx ); LL_TIM_GenerateEvent_UPDATE( TIMx ); pHandle->_Super.Step = pHandle->_Super.NextStep; retVal = true; } return retVal; } /** * @brief It checks whether the fastdemag configuration has been updated. * @param pHandle Pointer on the target component instance. * @retval bool FastDemag configuration has been updated */ __weak bool ThreePwm_IsFastDemagUpdated( PWMC_ThreePwm_Handle_t * pHandle ) { return (pHandle->FastDemagUpdated); } /** * @brief It resets the polarity of the timer PWM channel outputs to default. * @param pHandle Pointer on the target component instance. * @retval none */ __weak void ThreePwm_ResetOCPolarity( PWMC_ThreePwm_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, pHandle->pParams_str->OCPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, pHandle->pParams_str->OCPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, pHandle->pParams_str->OCPolarity); } /** * @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 ThreePwm_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_ThreePwm_Handle_t * pHandle = ( PWMC_ThreePwm_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, 0u); LL_TIM_OC_SetCompareCH2(TIMx, 0u); LL_TIM_OC_SetCompareCH3(TIMx, 0u); ThreePwm_ResetOCPolarity( pHandle ); LL_TIM_GenerateEvent_COM( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_SetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } /** * @brief This function enables the PWM outputs * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void ThreePwm_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_ThreePwm_Handle_t * pHandle = ( PWMC_ThreePwm_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; pHandle->DemagCounter = 0; LL_TIM_EnableIT_UPDATE( pHandle->pParams_str->TIMx ); /* Select the Capture Compare preload feature */ LL_TIM_CC_EnablePreload( TIMx ); /* Select the Commutation event source */ LL_TIM_CC_SetUpdate( TIMx, LL_TIM_CCUPDATESOURCE_COMG_ONLY ); LL_TIM_OC_SetCompareCH1(TIMx, 0u); LL_TIM_OC_SetCompareCH2(TIMx, 0u); LL_TIM_OC_SetCompareCH3(TIMx, 0u); LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); ThreePwm_ResetOCPolarity( pHandle ); LL_TIM_GenerateEvent_COM( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if (true == pHandle->Oversampling ) { LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_UPDATE); } else { LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); } } /** * @brief This function sets the capcture compare of the timer channel * used for ADC triggering * @param pHdl: handler of the current instance of the PWM component * @param SamplingPoint: trigger point * @retval none */ __weak void ThreePwm_SetADCTriggerChannel( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_ThreePwm_Handle_t * pHandle = ( PWMC_ThreePwm_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.ADCTriggerCnt = SamplingPoint; LL_TIM_OC_SetCompareCH4(TIMx, pHandle->_Super.ADCTriggerCnt); } /** * @brief It disables PWM generation on the proper Timer peripheral acting on * MOE bit and reset the TIM status * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void ThreePwm_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_ThreePwm_Handle_t * pHandle = ( PWMC_ThreePwm_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; ThreePwm_ResetEnablePins ( pHandle ); /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); LL_TIM_OC_SetCompareCH1(TIMx, 0u); LL_TIM_OC_SetCompareCH2(TIMx, 0u); LL_TIM_OC_SetCompareCH3(TIMx, 0u); pHandle->_Super.CntPh = 0; LL_TIM_DisableIT_UPDATE( pHandle->pParams_str->TIMx ); LL_TIM_SetTriggerOutput(pHandle->pParams_str->TIMx, LL_TIM_TRGO_RESET); return; } /** * @brief It contains the Break event interrupt * @param pHandle: handler of the current instance of the PWM component * @retval none */ __weak void * ThreePwm_BRK_IRQHandler( PWMC_ThreePwm_Handle_t * pHandle ) { pHandle->_Super.OverCurrentFlag = true; LL_TIM_DisableIT_UPDATE( pHandle->pParams_str->TIMx ); LL_TIM_ClearFlag_UPDATE( pHandle->pParams_str->TIMx ); return MC_NULL; } void ThreePwm_ResetEnablePins( PWMC_ThreePwm_Handle_t * pHandle ) { LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_u_port, pHandle->pParams_str->pwm_en_u_pin ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_v_port, pHandle->pParams_str->pwm_en_v_pin ); LL_GPIO_ResetOutputPin( pHandle->pParams_str->pwm_en_w_port, pHandle->pParams_str->pwm_en_w_pin ); } /** * @brief It is used to return the fast demagnetization flag. * @param pHdl: handler of the current instance of the PWM component * @retval uint16_t It returns 1 whether fast demag is active. */ __weak uint8_t ThreePwm_FastDemagFlag( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_ThreePwm_Handle_t * pHandle = ( PWMC_ThreePwm_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif return (pHandle->FastDemag); } /** * @brief This function updates the demagnetization counter * @param pHandle: handler of the current instance of the PWM component * @retval none */ __weak void ThreePwm_UpdatePwmDemagCounter( PWMC_ThreePwm_Handle_t * pHandle ) { pHandle->DemagCounter += LL_TIM_GetRepetitionCounter(TIM1) + 1; LL_TIM_EnableIT_UPDATE(TIM1); } /** * @brief This function disable the update of the demagnetization counter in the update event * @param pHandle: handler of the current instance of the PWM component * @retval none */ __weak void ThreePwm_DisablePwmDemagCounter( PWMC_ThreePwm_Handle_t * pHandle ) { LL_TIM_DisableIT_UPDATE(TIM1); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
28,077
C
39.341954
138
0.637105
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/inrush_current_limiter.c
/** ****************************************************************************** * @file inrush_current_limiter.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions implementing the * Inrush Current Limiter feature 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 ICL */ /* Includes ------------------------------------------------------------------*/ #include "inrush_current_limiter.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @defgroup ICL Inrush Current Limiter * @brief Inrush Current Limiter component of the Motor Control SDK * * Inrush current limiter acts on the NTC bypass relay according to the DC bus level in * order to limit the current when charging DC bulk capacitor. * In order to work properly, it needs to point on the Vbus and digital output handlers * to measure the DC bus and control the NTC bypass relay. Inrush current limiter has * its own state machine described below: * * ![](ICL_FSM.svg) * * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private defines -----------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Global variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief Initializes all the needed ICL component variables. * It shall be called only once during Motor Control initialization. * @param pHandle: handler of the current instance of the ICL component * @param pVBS the bus voltage sensor used by the ICL. * @param pDOUT the digital output used by the ICL. */ __weak void ICL_Init(ICL_Handle_t *pHandle, BusVoltageSensor_Handle_t *pVBS, DOUT_handle_t *pDOUT) { pHandle->pVBS = pVBS; pHandle->pDOUT = pDOUT; DOUT_SetOutputState(pDOUT, ACTIVE); } /** * @brief Executes the inrush current limiter state machine and shall be * called during background task. * @param pHandle handler of the current instance of the ICL component * @retval ICLState_t returns the current ICL state machine */ __weak ICL_State_t ICL_Exec(ICL_Handle_t *pHandle) { /* ICL actions.*/ switch (pHandle->ICLstate) { case ICL_ACTIVATION: { /* ICL activation: counting the step before pass in ICL_ACTIVE */ if (pHandle->hICLTicksCounter == 0u) { pHandle->ICLstate = ICL_ACTIVE; pHandle->hICLTicksCounter = pHandle->hICLChargingDelayTicks; } else { pHandle->hICLTicksCounter--; } } break; case ICL_DEACTIVATION: { /* ICL deactivation: counting the step before pass in ICL_INACTIVE.*/ if (pHandle->hICLTicksCounter == 0u) { pHandle->ICLstate = ICL_INACTIVE; } else { pHandle->hICLTicksCounter--; } } break; case ICL_ACTIVE: { /* ICL is active: if bus is present and capacitor charging time elapsed*/ if (pHandle->hICLTicksCounter == 0u) { if (VBS_GetAvBusVoltage_d(pHandle->pVBS) > pHandle->hICLVoltageThreshold){ DOUT_SetOutputState(pHandle->pDOUT, INACTIVE); pHandle->ICLstate = ICL_DEACTIVATION; pHandle->hICLTicksCounter = pHandle->hICLSwitchDelayTicks; } } else { pHandle->hICLTicksCounter--; } } break; case ICL_INACTIVE: { /* ICL is inactive: if bus is not present activate the ICL */ if (VBS_CheckVbus(pHandle->pVBS) == MC_UNDER_VOLT) { DOUT_SetOutputState(pHandle->pDOUT, ACTIVE); pHandle->ICLstate = ICL_ACTIVATION; pHandle->hICLTicksCounter = pHandle->hICLSwitchDelayTicks; } } break; case ICL_IDLE: default: { } break; } return pHandle->ICLstate; } /** * @brief Returns the current state of the ICL state machine. * @param pHandle: handler of the current instance of the ICL component * @retval ICLState_t returns the current ICL state machine */ __weak ICL_State_t ICL_GetState(ICL_Handle_t *pHandle) { return pHandle->ICLstate; } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,024
C
28.910714
98
0.552747
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/mathlib.c
/** ****************************************************************************** * @file mathlib.c * @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 * ****************************************************************************** */ /* mathlib.c */ #include "mathlib.h" #include <math.h> #include <stdlib.h> #include <stdbool.h> /* defines */ #define CST_LEN 128 #define _MTL (CST_LEN) // Max Cos table _MTL = 2^k, Actual length = _MTL+1. #define COSSIN_TABLESIZE _MTL #define COSSIN_FORMAT 15 #define _MNB 30 // Position of binary point. #define _BITS 24 // Maximum bits of precision. #define _MAXI _BITS+1 // Maximum number of Cordic iterations. #ifndef M_TWOPI #define M_TWOPI 6.28318530717958647f #endif /* Fixed point macros */ #define __CFIXPn(A, n) (int32_t) ((A) * powf(2.0f, n)) #define __CFIXPnmpy(a, b, n) ( (int32_t)(((int64_t) (a) * (b)) >> (n)) ) #define __CFIXPntoF(A, n) ((float_t)(((float_t) (A)) / powf(2.0f, n))) /* types */ typedef struct _DQL { int b; // bit precision. int tpk; // number of bits required to index length m table (m=128 -> s_tpk=7) int tablesize; // source table size (RAM table is (4xtablesize)+2 long) } dql, *DQL; // Int DQ structure prototype. typedef struct _DQI { // Cordic consts. int g; // pi/2, pi and 1. int hpi, pi, one; // Cordic tables. int atan[_MAXI]; // Cordic & bit precision. int n, b; } dqi, *DQI; /* variables */ /* RAM table */ // _cstl[k] = _RNDL(csti[k]*((float) _MPL)). // Extra point need for sin interpolation. long _cstl[4*_MTL+2]; dql cossin_instance = { .b = COSSIN_FORMAT /* fixp_t<n> format angle and output */ }; dqi cordic_instance = { .n = 15, /* cordic_iterations */ .b = 30 /* cordic_bits */ }; // Cos table: _RNDL(cos(i*pi/(2*_MTL))*(2 << _MNB)) long _cst_128[CST_LEN+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 }; /* function declarations */ void cos_sin_tabl_init(void); void cordic_initi(DQI zi); /* functions */ static inline int log2i(int m) { int p2 = 0, k = 1; // Find p2, m <= 2^p2. while (k < m) { p2++; k <<= 1; } return p2; } /* end of log2i() */ void cos_sin_tabl_init() { /* Not optimized, since we will be converting to a static table, pre-compiled */ DQL zi = &cossin_instance; int tablesize = COSSIN_TABLESIZE; int b = zi->b; int m4 = tablesize << 2; zi->tablesize = tablesize; // Find tpk, m = 2^tpk. zi->tpk = log2i(tablesize); /* number of bits required to index length m table. m=128 -> 7 */ // Difference bits. int bb = _MNB - b; // Decimation factor. int mk; mk = _MTL >> zi->tpk; // Quadrant = 0 cos. int i; int k; for (i = 0, k = 0; k <= _MTL; k += mk, i++) { _cstl[i] = _cst_128[k] >> bb; // Next lower 2 bits. long ths; ths = _cst_128[k] >> (bb - 2); // Next 2 lower bits on? if ((ths & 3) == 3) { // Round up. _cstl[i] += 1; } } // Quadrant = 1 cos. for (k = i, i = 0; i <= tablesize; i++) { _cstl[i+tablesize] = -_cstl[--k]; } // Quadrants = 2, 3 cos. for (i += tablesize, k = i-1; i <= m4; i++) { _cstl[i] = _cstl[--k]; } // Extra point. _cstl[i] = _cstl[i-1]; } /* end of cos_sin_tabl_init() */ // Assumes a normalized angle: 0 <= th/(2*pi) < 1. // Fast table z = cos(th) + j*sin(th) (long) precision, // for a value of th using 4*m+2 entry cos table + Taylor // extrapolation or linear interpolation, absolute. Vector_cossin_s MATHLIB_cossin(int32_t angle_pu) { /* scale of data is fixp_t<m> format, 15 is working, 30 is not. * * inputs: * thr angle theta in per unit (0 = 0 degrees, 1 = 360 degrees) * * outputs: * x cosine * y sine * * tables: * _cst_128 128 long cosine table, source data, could be in rom * _cstl 4*_MTL+2 = up to 514 long, derived table, in ram * */ DQL zi = &cossin_instance; // Number of bits. int b = zi->b; // table size int tablesize = zi->tablesize; // ths = |th|*m*4. /* shift left (multiply by 2^n) by tpk (7) + 2 = 9 */ /* ths = fixp15_t(0.999f) << 9, giving fixp24_t(0.999f) */ /* This causes fixp30_t angle to fail */ /* tpk comes from needing log2(m) bits to index the table */ /* the 2 comes from having 1/4 of a rotation in the table */ long ths = labs(angle_pu) << (zi->tpk + 2); // k = ths/m, 0 <= k < m. /* shift right by b=15, k is fixp9_t (for tablesize = 128), i.e. k becomes the index for the cosine value but ... */ /* fixp9_t(1.0f) = 512, the table is 1/4 of that. The 2 extra bits */ int k = (int) (ths >> b); /* k could be calculated in one step; */ /* k = _iq<b>toiq<s_tpk+2> = _iq15toiq9 */ /* k = th >> () */ // _q15 << (s_tkp + 2) >> b == _q15 << (7 + 2) >> 15 == _q15 >> 6 == conversion to _q9 // thf = (ths - k*m). // Note use of bit ops. long thf = ths & ~(k << b); /* used in linear interpolation / extrapolation */ /* k = index, top bits of angle */ /* k << b = top bits back in top bits place */ /* ~ is bitwise NOT, turning those bits off */ /* & masks the index bits off */ /* remainder after removing the k*m part */ // Cos value. long cs = _cstl[k]; // Modulo m4 index. /* sine table is cosine table + offset, values inverted? */ int mk = tablesize + k; /* sine index = tablesize + cosine index */ int m4 = tablesize << 2; // Table length * 4. if (mk > m4) /* wrap sine index (could be bit operation?) */ { mk -= m4; } // Sin value. long sn = -_cstl[mk]; /* mk is sine index, value is negated because sine table is -cosine table, with an offset? */ // Linear interpolation. cs += (((_cstl[k + 1] - cs) * thf) >> b); sn -= (((_cstl[mk + 1] + sn) * thf) >> b); /* linear interpolation for better, smoother result */ /* k+1 and mk+1 point to the next entry in the table * (_cstl[k+1]-cs) = delta to next (sine variant uses inverse values) * * thf multiplies with a fixp_t<b> format number (?), giving fixp_t<2*b> intermediate, >> b shifts back to fixp_t<b> format * (this limits the function to (1/2 * fixp32_t format), approx) * * cs += delta_next * thf * * thf must be linear factor dx/step */ Vector_cossin_s result; result.cos = cs; result.sin = sn; return result; } /* end of cos_sin_tabl_LX() */ // // zi->K factor & atanti for zi->n iterations. // Note: Should be called first for init. // void cordic_initi(DQI zi) { int k; /* Loop variable */ int g; /* term for gain[] calculation */ // Convert pi/2, pi, 3*pi/2, 2*pi and one. zi->one = __CFIXPn(1.0f, zi->b); /* Per unit angles */ zi->hpi = __CFIXPn(0.25f, zi->b); /* 1/2 PI, 90 degrees, 0.25f per unit */ zi->pi = __CFIXPn(0.5f, zi->b); /* PI, 180 degrees, 0.5f per unit */ // Initialize. g = zi->one; // Cordic tables & constants. for (k = 0; k < zi->n; k++) { // Cordic atan tables. /* floating point calculated variant */ { float_t slope = powf(2, -k); zi->atan[k] = __CFIXPn((atanf(slope) / M_TWOPI), zi->b); } // Gain table. if (k < 7) { g += (g >> 2*(k + 1)); } } // nth constants. float_t g_flt = __CFIXPntoF(g, zi->b); /* Convert g to floating point */ float_t gain_flt = 1.0f / sqrtf(g_flt); /* Calculate 1/sqrt(g) */ zi->g = __CFIXPn(gain_flt, zi->b); /* Convert result back to fixed point */ } /* end of cordic_initi() */ // Integer precision (int) version // to b bits of precision, b = zi->b. // Cordic algorithm to convert complex // cartesian to polar form. The input // is complex pair {x, y} where w = x + j*y // and the phase angle th = atan2(y, x). // Applies n iterations of Cordic algorithm // to rotate w to w' such that imag(w') = 0 // and thus |w'| = real(w'). The result is // multiplied by the Cordic gain g. Pass // address &zi of dqi data structure. // // Input: x = zi->x, y = zi->y, n = zi->n, // b = zi->b, and g = zi->g. // Output: th = zi->th, r = zi->r. // // cordic_cpoli(&zi); // void MATHLIB_polar(const int32_t x, const int32_t y, int32_t *angle_pu, int32_t *magnitude) { DQI zi = &cordic_instance; // Get |components|. int ax = abs(x); int ay = abs(y); // Swap x & y? bool swapped = false; if (ay > ax) { int temp = ax; ax = ay; ay = temp; swapped = true; } // Rotate y to zero. int sx; int sy; int th = 0; int k; for (k = 1; k < zi->n; k++) { // Cordic increment. sy = ay >> k; sx = ax >> k; // Cordic rotation. if (ay >= 0) { ax += sy; ay -= sx; th += zi->atan[k]; } else { ax -= sy; ay += sx; th -= zi->atan[k]; } } if (swapped) th = zi->hpi - th; /* x/y swapped */ if (x < 0) th = zi->pi - th; /* left half plane */ if (y < 0) th = zi->one - th; /* lower half plane */ *angle_pu = th; // Normalized magnitude. *magnitude = __CFIXPnmpy(ax, zi->g, zi->b); /* r = x*g */ } /* end of MATHLIB_polar() */ void MATHLIB_init() { /* Initialize cosine/sine table/object */ cos_sin_tabl_init(); /* Initialize cordic table/object */ cordic_initi(&cordic_instance); } /* end of MATHLIB_init() */ /* end of mathlib.c */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
11,000
C
25.444711
126
0.592727
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/encoder_speed_pos_fdbk.c
/** ****************************************************************************** * @file encoder_speed_pos_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the following features * of the Encoder component of the Motor Control SDK: * - computes and stores average mechanical speed * - computes and stores average mechanical acceleration * - computes and stores the instantaneous electrical speed * - calculates the rotor electrical and mechanical angle * ****************************************************************************** * @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 */ /* Includes ------------------------------------------------------------------*/ #include "encoder_speed_pos_fdbk.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @defgroup Encoder Encoder Speed & Position Feedback * @brief Quadrature Encoder based Speed & Position Feedback implementation * * This component is used in applications controlling a motor equipped with a quadrature encoder. * * This component uses the output of a quadrature encoder to provide a measure of the speed and * the motor rotor position. * * More detail in [Encoder Speed & Position Feedback module](rotor_speed_pos_feedback_qenc.md). * * @{ */ /* Private defines -----------------------------------------------------------*/ /** * @brief It initializes the hardware peripherals required for the speed position sensor management using ENCODER sensors. * @param pHandle: handler of the current instance of the encoder component */ __weak void ENC_Init(ENCODER_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB if (NULL == pHandle) { /* Nothing to do */ } else { #endif TIM_TypeDef *TIMx = pHandle->TIMx; uint8_t bufferSize; uint8_t index; #ifdef TIM_CNT_UIFCPY LL_TIM_EnableUIFRemap(TIMx); #define ENC_MAX_OVERFLOW_NB ((uint16_t)2048) /* 2^11*/ #else #define ENC_MAX_OVERFLOW_NB (1) #endif /* Reset counter */ LL_TIM_SetCounter(TIMx, 0); /*Calculations of convenience*/ pHandle->U32MAXdivPulseNumber = UINT32_MAX / ((uint32_t) pHandle->PulseNumber); pHandle->SpeedSamplingFreqUnit = ((uint32_t)pHandle->SpeedSamplingFreqHz * (uint32_t)SPEED_UNIT); /* Set IC filter for both channel 1 & 2 */ LL_TIM_IC_SetFilter(TIMx, LL_TIM_CHANNEL_CH1, ((uint32_t)pHandle->ICx_Filter)); LL_TIM_IC_SetFilter(TIMx, LL_TIM_CHANNEL_CH2, ((uint32_t)pHandle->ICx_Filter)); LL_TIM_ClearFlag_UPDATE(TIMx); LL_TIM_EnableIT_UPDATE(TIMx); /* Enable the counting timer */ LL_TIM_EnableCounter(TIMx); /* Erase speed buffer */ bufferSize = pHandle->SpeedBufferSize; for (index = 0U; index < bufferSize; index++) { pHandle->DeltaCapturesBuffer[index] = 0; } #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB } #endif } /** * @brief Clear software FIFO where the captured rotor angle variations are stored. * This function must be called before starting the motor to initialize * the speed measurement process. * @param pHandle: handler of the current instance of the encoder component */ __weak void ENC_Clear(ENCODER_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB if (NULL == pHandle) { /* Nothing to do */ } else { #endif uint8_t index; for (index = 0u; index < pHandle->SpeedBufferSize; index++) { pHandle->DeltaCapturesBuffer[index] = 0; } pHandle->SensorIsReliable = true; #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB } #endif } /** * @brief It calculates the rotor electrical and mechanical angle, on the basis * of the instantaneous value of the timer counter. * @param pHandle: handler of the current instance of the encoder component * @retval Measured electrical angle in [s16degree](measurement_units.md) format. */ __weak int16_t ENC_CalcAngle(ENCODER_Handle_t *pHandle) { int16_t elAngle; /* s16degree format */ #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB if (NULL == pHandle) { elAngle = 0; } else { #endif int16_t mecAngle; /* s16degree format */ uint32_t uwtemp1; int32_t wtemp1; /* PR 52926 We need to keep only the 16 LSB, bit 31 could be at 1 if the overflow occurs just after the entry in the High frequency task */ uwtemp1 = (LL_TIM_GetCounter(pHandle->TIMx) & 0xffffU) * (pHandle->U32MAXdivPulseNumber); #ifndef FULL_MISRA_C_COMPLIANCY_ENC_SPD_POS wtemp1 = (int32_t)uwtemp1 >> 16U; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 #else wtemp1 = (int32_t)uwtemp1 / 65536; #endif /* Computes and stores the rotor mechanical angle */ mecAngle = (int16_t)wtemp1; int16_t hMecAnglePrev = pHandle->_Super.hMecAngle; pHandle->_Super.hMecAngle = mecAngle; /* Computes and stores the rotor electrical angle */ elAngle = mecAngle * (int16_t)(pHandle->_Super.bElToMecRatio); pHandle->_Super.hElAngle = elAngle; int16_t hMecSpeedDpp = mecAngle - hMecAnglePrev; pHandle->_Super.wMecAngle += ((int32_t)hMecSpeedDpp); #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB } #endif /*Returns rotor electrical angle*/ return (elAngle); } /** * @brief This method must be called with the periodicity defined by parameter * SpeedSamplingFreqUnit. The method generates a capture event on * a channel, computes and stores average mechanical speed expressed in the unit * defined by #SPEED_UNIT (on the basis of the buffer filled by Medium Frequency Task), * computes and stores average mechanical acceleration expressed in #SPEED_UNIT/SpeedSamplingFreq, * computes and stores the instantaneous electrical speed in Digit Per control Period * unit [dpp](measurement_units.md), updates the index of the * speed buffer, then checks, stores and returns the reliability state * of the sensor. * @param pHandle: handler of the current instance of the encoder component * @param pMecSpeedUnit pointer used to return the rotor average mechanical speed * expressed in the unit defined by #SPEED_UNIT * @retval true = sensor information is reliable. false = sensor information is not reliable */ __weak bool ENC_CalcAvrgMecSpeedUnit(ENCODER_Handle_t *pHandle, int16_t *pMecSpeedUnit) { bool bReliability; #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB if ((NULL == pHandle) || (NULL == pMecSpeedUnit)) { bReliability = false; } else { #endif int32_t wtemp1; int32_t wtemp2; uint32_t OverflowCntSample; uint32_t CntCapture; uint32_t directionSample; int32_t wOverallAngleVariation = 0; TIM_TypeDef *TIMx = pHandle->TIMx; uint8_t bBufferSize = pHandle->SpeedBufferSize; uint8_t bBufferIndex; #ifdef TIM_CNT_UIFCPY uint8_t OFbit; #else uint8_t OFbit = 0U; #endif #ifdef TIM_CNT_UIFCPY /* disable Interrupt generation */ LL_TIM_DisableIT_UPDATE(TIMx); #endif CntCapture = LL_TIM_GetCounter(TIMx); OverflowCntSample = pHandle->TimerOverflowNb; pHandle->TimerOverflowNb = 0; directionSample = LL_TIM_GetDirection(TIMx); #ifdef TIM_CNT_UIFCPY OFbit = __LL_TIM_GETFLAG_UIFCPY(CntCapture); if (0U == OFbit) { /* Nothing to do */ } else { /* If OFbit is set, overflow has occured since IT has been disabled. We have to take this overflow into account in the angle computation, but we must not take it into account a second time in the accmulator, so we have to clear the pending flag. If the OFbit is not set, it does not mean that an Interrupt has not occured since the last read, but it has not been taken into accout, we must not clear the interrupt in order to accumulate it */ LL_TIM_ClearFlag_UPDATE(TIMx); } LL_TIM_EnableIT_UPDATE(TIMx); CLEAR_BIT(CntCapture, TIM_CNT_UIFCPY); #endif /* If UIFCPY is not present, OverflowCntSample can not be used safely for speed computation, but we still use it to check that we do not exceed one overflow (sample frequency not less than mechanical motor speed */ if ((OverflowCntSample + OFbit) > ENC_MAX_OVERFLOW_NB) { pHandle->TimerOverflowError = true; } else { /* Nothing to do */ } /* Calculation of delta angle */ if (LL_TIM_COUNTERDIRECTION_DOWN == directionSample) { /* Encoder timer down-counting */ /* If UIFCPY not present Overflow counter can not be safely used -> limitation to 1 OF */ #ifndef TIM_CNT_UIFCPY OverflowCntSample = (CntCapture > pHandle->PreviousCapture) ? 1 : 0; #endif pHandle->DeltaCapturesBuffer[pHandle->DeltaCapturesIndex] = ((int32_t)CntCapture) - ((int32_t)pHandle->PreviousCapture) - ((((int32_t)OverflowCntSample) + (int32_t)OFbit) * ((int32_t)pHandle->PulseNumber)); } else { /* Encoder timer up-counting */ /* If UIFCPY not present Overflow counter can not be safely used -> limitation to 1 OF */ #ifndef TIM_CNT_UIFCPY OverflowCntSample = (CntCapture < pHandle->PreviousCapture) ? 1 : 0; #endif pHandle->DeltaCapturesBuffer[pHandle->DeltaCapturesIndex] = ((int32_t)CntCapture) - ((int32_t)pHandle->PreviousCapture) + ((((int32_t)OverflowCntSample) + (int32_t)OFbit) * ((int32_t)pHandle->PulseNumber)); } /* Computes & returns average mechanical speed */ for (bBufferIndex = 0U; bBufferIndex < bBufferSize; bBufferIndex++) { wOverallAngleVariation += pHandle->DeltaCapturesBuffer[bBufferIndex]; } wtemp1 = wOverallAngleVariation * ((int32_t)pHandle->SpeedSamplingFreqUnit); wtemp2 = ((int32_t)pHandle->PulseNumber) * ((int32_t)pHandle->SpeedBufferSize); wtemp1 = ((0 == wtemp2) ? wtemp1 : (wtemp1 / wtemp2)); *pMecSpeedUnit = (int16_t)wtemp1; /* Computes & stores average mechanical acceleration */ pHandle->_Super.hMecAccelUnitP = (int16_t)(wtemp1 - pHandle->_Super.hAvrMecSpeedUnit); /* Stores average mechanical speed */ pHandle->_Super.hAvrMecSpeedUnit = (int16_t)wtemp1; /* Computes & stores the instantaneous electrical speed [dpp], var wtemp1 */ wtemp1 = pHandle->DeltaCapturesBuffer[pHandle->DeltaCapturesIndex] * ((int32_t)pHandle->SpeedSamplingFreqHz) * ((int32_t)pHandle->_Super.bElToMecRatio); wtemp1 /= ((int32_t)pHandle->PulseNumber); wtemp1 *= ((int32_t)pHandle->_Super.DPPConvFactor); wtemp1 /= ((int32_t)pHandle->_Super.hMeasurementFrequency); pHandle->_Super.hElSpeedDpp = (int16_t)wtemp1; /* Last captured value update */ pHandle->PreviousCapture = (CntCapture >= (uint32_t)65535) ? 65535U : (uint16_t)CntCapture; /*Buffer index update*/ pHandle->DeltaCapturesIndex++; if (pHandle->DeltaCapturesIndex >= pHandle->SpeedBufferSize) { pHandle->DeltaCapturesIndex = 0U; } else { /* Nothing to do */ } /* Checks the reliability status, then stores and returns it */ if (pHandle->TimerOverflowError) { bReliability = false; pHandle->SensorIsReliable = false; pHandle->_Super.bSpeedErrorNumber = pHandle->_Super.bMaximumSpeedErrorsNumber; } else { bReliability = SPD_IsMecSpeedReliable(&pHandle->_Super, pMecSpeedUnit); } #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB } #endif return (bReliability); } /** * @brief It set instantaneous rotor mechanical angle. * As a consequence, timer counter is computed and updated. * @param pHandle: handler of the current instance of the encoder component * @param hMecAngle new value of rotor mechanical angle in [s16degree](measurement_units.md) format. */ __weak void ENC_SetMecAngle(ENCODER_Handle_t *pHandle, int16_t hMecAngle) { #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB if (NULL == pHandle) { /* Nothing to do */ } else { #endif TIM_TypeDef *TIMx = pHandle->TIMx; uint16_t hAngleCounts; uint16_t hMecAngleuint; int16_t localhMecAngle = hMecAngle; pHandle->_Super.hMecAngle = localhMecAngle; pHandle->_Super.hElAngle = localhMecAngle * (int16_t)pHandle->_Super.bElToMecRatio; if (localhMecAngle < 0) { localhMecAngle *= -1; hMecAngleuint = ((uint16_t)65535 - ((uint16_t)localhMecAngle)); } else { hMecAngleuint = (uint16_t)localhMecAngle; } hAngleCounts = (uint16_t)((((uint32_t)hMecAngleuint) * ((uint32_t)pHandle->PulseNumber)) / 65535U); TIMx->CNT = (uint16_t)hAngleCounts; #ifdef NULL_PTR_CHECK_ENC_SPD_POS_FDB } #endif } /** * @brief TIMER ENCODER Overflow interrupt counter update * @param pHandleVoid: handler of the current instance of the encoder component */ __weak void *ENC_IRQHandler(void *pHandleVoid) { ENCODER_Handle_t *pHandle = (ENCODER_Handle_t *)pHandleVoid; //cstat !MISRAC2012-Rule-11.5 /* Updates the number of overflows occurred */ /* The handling of overflow error is done in ENC_CalcAvrgMecSpeedUnit */ pHandle->TimerOverflowNb += 1U; return (MC_NULL); } /** * @} */ /** * @} */ /** @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
13,748
C
31.735714
112
0.654204
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/pwmc_6pwm.c
/** ****************************************************************************** * @file pwmc_6pwm.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides the firmware functions that implement the * pwmc_6pwm 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_6pwm */ /* Includes ------------------------------------------------------------------*/ #include "pwmc_6pwm.h" #include "pwm_common_sixstep.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk_6s * @{ */ /** * @defgroup pwmc_6pwm Six-Step, 6 signals PWM generation * * @brief PWM generation implementation for Six-Step drive with 6 PWM duty cycles * * This implementation drives both the high sides and the low sides of the bridges. * * @todo: Complete documentation. * @{ */ /* Private defines -----------------------------------------------------------*/ #define TIMxCCER_MASK_CH123 (LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH3 ) #define TIMxCCER_MASK_CH1N2N3N (LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3N) /* Private function prototypes -----------------------------------------------*/ /** * @brief It initializes TIMx, DMA1 and NVIC * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void SixPwm_Init( PWMC_SixPwm_Handle_t * pHandle ) { if ( ( uint32_t )pHandle == ( uint32_t )&pHandle->_Super ) { /* Enable the CCS */ LL_RCC_HSE_EnableCSS(); /* Peripheral clocks enabling END ----------------------------------------*/ /* Clear TIMx break flag. */ LL_TIM_ClearFlag_BRK( pHandle->pParams_str->TIMx ); LL_TIM_EnableIT_BRK( pHandle->pParams_str->TIMx ); LL_TIM_ClearFlag_UPDATE( pHandle->pParams_str->TIMx ); /* disable ADC source trigger */ LL_TIM_SetTriggerOutput(pHandle->pParams_str->TIMx, LL_TIM_TRGO_RESET); /* Enable PWM channel */ LL_TIM_CC_EnableChannel( pHandle->pParams_str->TIMx, TIMxCCER_MASK_CH123 | TIMxCCER_MASK_CH1N2N3N ); /* Clear the flags */ pHandle->_Super.OverVoltageFlag = false; pHandle->_Super.OverCurrentFlag = false; pHandle->_Super.driverProtectionFlag = false; pHandle->FastDemagUpdated = true; pHandle->_Super.hElAngle = 0; LL_TIM_EnableCounter( pHandle->pParams_str->TIMx ); if (pHandle->pParams_str->OCPolarity == LL_TIM_OCPOLARITY_HIGH) { pHandle->NegOCPolarity = LL_TIM_OCPOLARITY_LOW; } else { pHandle->NegOCPolarity = LL_TIM_OCPOLARITY_HIGH; } if (pHandle->pParams_str->OCNPolarity == LL_TIM_OCPOLARITY_HIGH) { pHandle->NegOCNPolarity = LL_TIM_OCPOLARITY_LOW; } else { pHandle->NegOCNPolarity = LL_TIM_OCPOLARITY_HIGH; } } } /** * @brief It updates the stored duty cycle variable. * @param pHandle Pointer on the target component instance. * @param new duty cycle value. * @retval none */ __weak void PWMC_SetPhaseVoltage( PWMC_Handle_t * pHandle, uint16_t DutyCycle ) { pHandle->CntPh = DutyCycle; } /** * @brief It writes the duty cycle into timer shadow registers. * @param pHandle Pointer on the target component instance. * @retval none */ __weak void SixPwm_LoadNextStep( PWMC_SixPwm_Handle_t * pHandle, int16_t Direction ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.NextStep = PWMC_ElAngleToStep(&(pHandle->_Super)); if (pHandle->_Super.Step != pHandle->_Super.NextStep) { pHandle->DemagCounter = 0; if (pHandle->_Super.ModUpdateReq == ENABLE_FAST_DEMAG) { pHandle->FastDemag = true; pHandle->_Super.ModUpdateReq = NO_REQUEST; } if (pHandle->_Super.ModUpdateReq == DISABLE_FAST_DEMAG) { SixPwm_ResetOCPolarity(pHandle); LL_TIM_GenerateEvent_COM( TIMx ); pHandle->FastDemag = false; pHandle->_Super.ModUpdateReq = NO_REQUEST; } if (pHandle->_Super.ModUpdateReq == ENABLE_QUASI_SYNCH) { pHandle->QuasiSynchDecay = true; pHandle->_Super.ModUpdateReq = NO_REQUEST; } if (pHandle->_Super.ModUpdateReq == DISABLE_QUASI_SYNCH) { pHandle->QuasiSynchDecay = false; pHandle->_Super.ModUpdateReq = NO_REQUEST; } } /* Quasi-synchronous rectification */ if ( pHandle->QuasiSynchDecay == true) { switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N | LL_TIM_CHANNEL_CH1N); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH1N); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2N); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N | LL_TIM_CHANNEL_CH2N); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH3); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3N); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH3N); } break; } } /* Fast demagnetization */ else if (( pHandle->FastDemag == true ) && ( pHandle->DemagCounter < (pHandle->_Super.DemagCounterThreshold ))) { uint16_t CWFastDemagPulse, CCWFastDemagPulse; uint32_t CWFastDemagPolarity, CWFastDemagNPolarity, CCWFastDemagPolarity, CCWFastDemagNPolarity; pHandle->FastDemagUpdated = false; if (Direction > 0) { CWFastDemagPulse = pHandle->_Super.CntPh; CCWFastDemagPulse = 0; CWFastDemagPolarity = pHandle->NegOCPolarity; CWFastDemagNPolarity = pHandle->NegOCNPolarity; CCWFastDemagPolarity = pHandle->pParams_str->OCPolarity; CCWFastDemagNPolarity = pHandle->pParams_str->OCNPolarity; } else { CWFastDemagPulse = 0; CCWFastDemagPulse = pHandle->_Super.CntPh; CWFastDemagPolarity = pHandle->pParams_str->OCPolarity; CWFastDemagNPolarity = pHandle->pParams_str->OCNPolarity; CCWFastDemagPolarity = pHandle->NegOCPolarity; CCWFastDemagNPolarity = pHandle->NegOCNPolarity; } switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1N, CWFastDemagNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2N, CWFastDemagNPolarity); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1N, CCWFastDemagNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3N, CCWFastDemagNPolarity); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2N, CWFastDemagNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3N, CWFastDemagNPolarity); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1N, CCWFastDemagNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2N, CCWFastDemagNPolarity); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1N, CWFastDemagNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3N, CWFastDemagNPolarity); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, CCWFastDemagPulse ); LL_TIM_OC_SetCompareCH3 ( TIMx, CWFastDemagPulse ); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, CCWFastDemagPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2N, CCWFastDemagNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3N, CCWFastDemagNPolarity); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N ); } break; } } /* Alignment between two adjacent steps, CW direction*/ else if ( pHandle->_Super.AlignFlag == 1 ) { switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); } break; } LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N); } /* Alignment between two adjacent steps, CCW direction*/ else if ( pHandle->_Super.AlignFlag == -1 ) { switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); } break; } LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N); } /* standard configuration */ else { if (pHandle->DemagCounter >= pHandle->_Super.DemagCounterThreshold ) { pHandle->FastDemagUpdated = true; SixPwm_ResetOCPolarity(pHandle); LL_TIM_GenerateEvent_COM( TIMx ); } switch ( pHandle->_Super.NextStep ) { case STEP_1: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); } break; case STEP_2: { LL_TIM_OC_SetCompareCH1 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N ); } break; case STEP_3: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N ); } break; case STEP_4: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_OC_SetCompareCH3 ( TIMx, 0 ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); } break; case STEP_5: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N ); } break; case STEP_6: { LL_TIM_OC_SetCompareCH1 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH2 ( TIMx, 0 ); LL_TIM_OC_SetCompareCH3 ( TIMx, (uint32_t)pHandle->_Super.CntPh ); LL_TIM_CC_EnableChannel( TIMx, LL_TIM_CHANNEL_CH2 | LL_TIM_CHANNEL_CH2N | LL_TIM_CHANNEL_CH3 | LL_TIM_CHANNEL_CH3N ); LL_TIM_CC_DisableChannel( TIMx, LL_TIM_CHANNEL_CH1 | LL_TIM_CHANNEL_CH1N ); } break; } } } /** * @brief It uploads the values into registers. * @param pHandle Pointer on the target component instance. * @retval bool Registers have been updated */ __weak bool SixPwm_ApplyNextStep( PWMC_SixPwm_Handle_t * pHandle ) { bool retVal = false; TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; if (pHandle->_Super.Step != pHandle->_Super.NextStep) { LL_TIM_GenerateEvent_COM( TIMx ); LL_TIM_GenerateEvent_UPDATE( TIMx ); pHandle->_Super.Step = pHandle->_Super.NextStep; retVal = true; } return retVal; } /** * @brief It checks whether the fastdemag configuration has been updated. * @param pHandle Pointer on the target component instance. * @retval bool FastDemag configuration has been updated */ __weak bool SixPwm_IsFastDemagUpdated( PWMC_SixPwm_Handle_t * pHandle ) { return (pHandle->FastDemagUpdated); } /** * @brief It resets the polarity of the timer PWM channel outputs to default. * @param pHandle Pointer on the target component instance. * @retval none */ __weak void SixPwm_ResetOCPolarity( PWMC_SixPwm_Handle_t * pHandle ) { TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1, pHandle->pParams_str->OCPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH1N, pHandle->pParams_str->OCNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2, pHandle->pParams_str->OCPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH2N, pHandle->pParams_str->OCNPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3, pHandle->pParams_str->OCPolarity); LL_TIM_OC_SetPolarity( TIMx, LL_TIM_CHANNEL_CH3N, pHandle->pParams_str->OCNPolarity); } /** * @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 SixPwm_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_SixPwm_Handle_t * pHandle = ( PWMC_SixPwm_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, 0u); LL_TIM_OC_SetCompareCH2(TIMx, 0u); LL_TIM_OC_SetCompareCH3(TIMx, 0u); SixPwm_ResetOCPolarity(pHandle); LL_TIM_GenerateEvent_COM( TIMx ); /* Main PWM Output Enable */ LL_TIM_EnableAllOutputs(TIMx); } /** * @brief This function enables the PWM outputs * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void SixPwm_SwitchOnPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_SixPwm_Handle_t * pHandle = ( PWMC_SixPwm_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; pHandle->DemagCounter = 0; LL_TIM_EnableIT_UPDATE( pHandle->pParams_str->TIMx ); /* Select the Capture Compare preload feature */ LL_TIM_CC_EnablePreload( TIMx ); /* Select the Commutation event source */ LL_TIM_CC_SetUpdate( TIMx, LL_TIM_CCUPDATESOURCE_COMG_ONLY ); LL_TIM_OC_SetCompareCH1(TIMx, 0u); LL_TIM_OC_SetCompareCH2(TIMx, 0u); LL_TIM_OC_SetCompareCH3(TIMx, 0u); LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH1, LL_TIM_OCMODE_PWM1 ); LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH2, LL_TIM_OCMODE_PWM1 ); LL_TIM_OC_SetMode( TIMx, LL_TIM_CHANNEL_CH3, LL_TIM_OCMODE_PWM1 ); SixPwm_ResetOCPolarity( pHandle ); LL_TIM_GenerateEvent_COM( TIMx ); /* Main PWM Output Enable */ TIMx->BDTR |= LL_TIM_OSSI_ENABLE; LL_TIM_EnableAllOutputs(TIMx); if (true == pHandle->Oversampling ) { LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_UPDATE); } else { LL_TIM_SetTriggerOutput(TIMx, LL_TIM_TRGO_OC4REF); } } /** * @brief This function sets the capcture compare of the timer channel * used for ADC triggering * @param pHdl: handler of the current instance of the PWM component * @param SamplingPoint: trigger point * @retval none */ __weak void SixPwm_SetADCTriggerChannel( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_SixPwm_Handle_t * pHandle = ( PWMC_SixPwm_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif TIM_TypeDef * TIMx = pHandle->pParams_str->TIMx; pHandle->_Super.ADCTriggerCnt = SamplingPoint; LL_TIM_OC_SetCompareCH4(TIMx, pHandle->_Super.ADCTriggerCnt); } /** * @brief It disables PWM generation on the proper Timer peripheral acting on * MOE bit and reset the TIM status * @param pHdl: handler of the current instance of the PWM component * @retval none */ __weak void SixPwm_SwitchOffPWM( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_SixPwm_Handle_t * pHandle = ( PWMC_SixPwm_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; /* Main PWM Output Disable */ LL_TIM_DisableAllOutputs(TIMx); LL_TIM_OC_SetCompareCH1(TIMx, 0u); LL_TIM_OC_SetCompareCH2(TIMx, 0u); LL_TIM_OC_SetCompareCH3(TIMx, 0u); pHandle->_Super.CntPh = 0; LL_TIM_DisableIT_UPDATE( pHandle->pParams_str->TIMx ); LL_TIM_SetTriggerOutput(pHandle->pParams_str->TIMx, LL_TIM_TRGO_RESET); return; } /** * @brief It contains the Break event interrupt * @param pHandle: handler of the current instance of the PWM component * @retval none */ __weak void * SixPwm_BRK_IRQHandler( PWMC_SixPwm_Handle_t * pHandle ) { pHandle->_Super.OverCurrentFlag = true; LL_TIM_DisableIT_UPDATE( pHandle->pParams_str->TIMx ); LL_TIM_ClearFlag_UPDATE( pHandle->pParams_str->TIMx ); return MC_NULL; } /** * @brief It is used to return the fast demagnetization flag. * @param pHdl: handler of the current instance of the PWM component * @retval uint16_t It returns 1 whether fast demag is active. */ __weak uint8_t SixPwm_FastDemagFlag( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_SixPwm_Handle_t * pHandle = ( PWMC_SixPwm_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif return (pHandle->FastDemag); } /** * @brief It is used to return the quasi-synchronous rectification flag. * @param pHdl: handler of the current instance of the PWM component * @retval uint16_t It returns 1 whether quasi-synch feature is active. */ __weak uint8_t SixPwm_QuasiSynchFlag( PWMC_Handle_t * pHdl ) { #if defined (__ICCARM__) #pragma cstat_disable = "MISRAC2012-Rule-11.3" #endif PWMC_SixPwm_Handle_t * pHandle = ( PWMC_SixPwm_Handle_t * )pHdl; #if defined (__ICCARM__) #pragma cstat_restore = "MISRAC2012-Rule-11.3" #endif return (pHandle->QuasiSynchDecay); } /** * @brief This function updates the demagnetization counter * @param pHandle: handler of the current instance of the PWM component * @retval none */ __weak void SixPwm_UpdatePwmDemagCounter( PWMC_SixPwm_Handle_t * pHandle ) { pHandle->DemagCounter += LL_TIM_GetRepetitionCounter(TIM1) + 1; LL_TIM_EnableIT_UPDATE(TIM1); } /** * @brief This function disable the update of the demagnetization counter in the update event * @param pHandle: handler of the current instance of the PWM component * @retval none */ __weak void SixPwm_DisablePwmDemagCounter( PWMC_SixPwm_Handle_t * pHandle ) { LL_TIM_DisableIT_UPDATE(TIM1); } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
28,163
C
36.552
165
0.620708
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/profiler_dcac.c
/** ****************************************************************************** * @file profiler_dcac.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions of profiler DC/AC * 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 * ****************************************************************************** * */ /* Includes ------------------------------------------------------------------*/ #include "profiler_dcac.h" #include "mc_math.h" void PROFILER_DCAC_stateMachine(PROFILER_DCAC_Handle handle, MOTOR_Handle motor); /** * @brief todo */ void PROFILER_DCAC_init(PROFILER_DCAC_Handle handle) { handle->state = PROFILER_DCAC_STATE_Idle; } /** * @brief todo */ void PROFILER_DCAC_setParams(PROFILER_DCAC_Handle handle, PROFILER_Params* pParams) { handle->background_rate_hz = pParams->background_rate_hz; /* Number of medium frequency task cycles in the dc measurement time */ PROFILER_DCAC_setMeasurementTime(handle, pParams->dcac_measurement_time_s); handle->CurToRamp_sf_pu = FIXP30(1.0f / pParams->dcac_current_ramping_time_s / pParams->background_rate_hz); /* duty setpoint */ handle->duty_maxgoal_pu = FIXP30(pParams->dcac_duty_maxgoal); handle->ac_freqkHz_pu = FIXP30(pParams->dcac_ac_freq_Hz / 1000.0f); handle->dc_duty_pu = FIXP30(0.0f); handle->ac_duty_pu = FIXP30(0.0f); handle->PowerDC_goal_W = pParams->dcac_PowerDC_goal_W; /* Current setpoint */ handle->Id_dc_max_pu = FIXP30(pParams->dcac_DCmax_current_A / pParams->fullScaleCurrent_A); /* Ramp rate */ handle->ramp_rate_duty_per_cycle = FIXP30(pParams->dcac_duty_maxgoal / pParams->dcac_duty_ramping_time_s / pParams->background_rate_hz); handle->fullScaleVoltage_V = pParams->fullScaleVoltage_V; handle->fullScaleCurrent_A = pParams->fullScaleCurrent_A; handle->voltagefilterpole_rps = pParams->voltagefilterpole_rps; handle->CurToRamp_sf_pu = FIXP30(1.0f / pParams->fullScaleCurrent_A / pParams->dcac_current_ramping_time_s / pParams->background_rate_hz); handle->glue_dcac_fluxestim_on = pParams->glue_dcac_fluxestim_on; } /** * @brief todo */ void PROFILER_DCAC_run(PROFILER_DCAC_Handle handle, MOTOR_Handle motor) { /* This function is called from the high frequency task / motor control interrupt */ /* After Sensorless and CurrentControl, so the DQ-values are available */ { /* Calculate filtered voltages and currents */ Voltages_Udq_t Udq = motor->pCurrCtrl->Udq_in_pu; Currents_Idq_t Idq = motor->pCurrCtrl->Idq_in_pu; /* Run filters with wLP = fs/(2^filtshift) (rad/sec) */ int filtshift = 10; handle->UdqLP.D += (Udq.D - handle->UdqLP.D) >> filtshift; handle->UdqLP.Q += (Udq.Q - handle->UdqLP.Q) >> filtshift; handle->IdqLP.D += (Idq.D - handle->IdqLP.D) >> filtshift; handle->IdqLP.Q += (Idq.Q - handle->IdqLP.Q) >> filtshift; } switch (handle->state) { case PROFILER_DCAC_STATE_AC_Measuring: { /* During AC Measuring state, use the ZEST injection as a duty injection */ Duty_Ddq_t Ddq; ZEST_getIdq_ref_inject_pu(motor->pSPD->pZeST, &Ddq); /* AC component for injection */ motor->pCurrCtrl->Ddq_ref_pu.D = handle->dc_duty_pu + Ddq.D; } break; default: /* Nothing to do */ break; } } /** * @brief todo */ void PROFILER_DCAC_runBackground(PROFILER_DCAC_Handle handle, MOTOR_Handle motor) { /* This function is called from the medium frequency task */ /* Counter counts down */ if (handle->counter > 0) handle->counter--; switch (handle->state) { /* Duty ramping */ case PROFILER_DCAC_STATE_RampUp: { fixp30_t ramp_rate = handle->ramp_rate_duty_per_cycle; fixp30_t delta_pu = handle->duty_maxgoal_pu - handle->dc_duty_pu; /* delta = target - current */ handle->dc_duty_pu += FIXP_sat(delta_pu, ramp_rate, -ramp_rate); motor->pCurrCtrl->Ddq_ref_pu.D = handle->dc_duty_pu; } break; case PROFILER_DCAC_STATE_DC_Measuring: motor->pCurrCtrl->Ddq_ref_pu.D = handle->dc_duty_pu; break; case PROFILER_DCAC_STATE_AC_Measuring: /* update duty performed in PROFILER_DCAC_run() function */ break; case PROFILER_DCAC_STATE_DConly: motor->pCurrCtrl->Ddq_ref_pu.D = handle->dc_duty_pu; break; case PROFILER_DCAC_STATE_RampDown: { fixp30_t ramp_rate = handle->ramp_rate_duty_per_cycle; fixp30_t delta_pu = 0 - handle->dc_duty_pu; /* delta = target - current */ handle->dc_duty_pu += FIXP_sat(delta_pu, ramp_rate, -ramp_rate); motor->pCurrCtrl->Ddq_ref_pu.D = handle->dc_duty_pu; } break; case PROFILER_DCAC_STATE_Idle: /* No break */ case PROFILER_DCAC_STATE_Complete: /* No break */ case PROFILER_DCAC_STATE_Error: /* Nothing to do in these states */ break; } PROFILER_DCAC_stateMachine(handle, motor); } /** * @brief todo */ void PROFILER_DCAC_reset(PROFILER_DCAC_Handle handle, MOTOR_Handle motor) { /* This is called before starting the DCAC process, and when the user aborts the Profiling */ /* Reset the DCAC state */ handle->state = PROFILER_DCAC_STATE_Idle; handle->error = PROFILER_DCAC_ERROR_None; /* Stop any ongoing actions */ motor->pSPD->zestControl.enableControlUpdate = true; motor->pSPD->flagHsoAngleEqualsOpenLoopAngle = false; motor->pCurrCtrl->Ddq_ref_pu.D = 0; motor->pCurrCtrl->Ddq_ref_pu.Q = 0; /* Reset duty reached */ handle->dc_duty_pu = 0; } /** * @brief todo */ void PROFILER_DCAC_stateMachine(PROFILER_DCAC_Handle handle, MOTOR_Handle motor) { PROFILER_DCAC_State_e state = handle->state; PROFILER_DCAC_State_e newState = state; switch (state) { case PROFILER_DCAC_STATE_Idle: /* Only called when profiler active */ /* Set motor to required state */ { /* Open loop angle, using duty reference Ddq_ref_pu */ //motor->flagEnableClosedLoopAngle = false; motor->pSTC->SpeedControlEnabled = false; motor->pCurrCtrl->forceZeroPwm = false; motor->pSPD->OpenLoopAngle = FIXP30(0.0f); motor->pCurrCtrl->Ddq_ref_pu.D = 0; motor->pCurrCtrl->Ddq_ref_pu.Q = 0; motor->pSTC->speedref_source = FOC_SPEED_SOURCE_Default; motor->pSTC->speed_ref_active_pu = 0; motor->pSTC->speed_ref_ramped_pu = 0; motor->pSTC->speed_ref_pu = FIXP30(0.0f); motor->pSPD->zestControl.enableControlUpdate = false; /* Disable MC_ZEST_Control_Update() */ motor->pSPD->flagHsoAngleEqualsOpenLoopAngle = true; /* theta, cosTh and sinTh of HSO equal to openloopAngle */ ZEST_setInjectMode(motor->pSPD->pZeST, ZEST_INJECTMODE_Auto); motor->pSPD->flagDisableImpedanceCorrection = true; IMPEDCORR_setRs(motor->pSPD->pImpedCorr, 0, 20); //set R and L to zero IMPEDCORR_setLs(motor->pSPD->pImpedCorr, 0, 20); handle->dc_duty_pu = 0; handle->ac_duty_pu = 0; handle->Id_dc_ref_pu = handle->Id_dc_max_pu; //reset initial current setpoint to max. handle->PowerDC_goal_pu = FIXP30(1.0f/1.5f * handle->PowerDC_goal_W / (handle->fullScaleCurrent_A * handle->fullScaleVoltage_V)); } newState = PROFILER_DCAC_STATE_RampUp; break; case PROFILER_DCAC_STATE_RampUp: { Currents_Idq_t Idq = motor->pCurrCtrl->Idq_in_pu; FIXP_CosSin_t cossin_park; FIXP30_CosSinPU(motor->pCurrCtrl->angle_park_pu, &cossin_park); Voltages_Udq_t Udq = MCM_Park_Voltage(motor->pPWM->Uab_in_pu, &cossin_park); fixp30_t Umag = FIXP_mag(Udq.D, Udq.Q); fixp30_t Imag = FIXP_mag(Idq.D, Idq.Q); fixp30_t Pmag = FIXP30_mpy(Umag, Imag); handle->PowerDC_W = 1.5f * FIXP30_toF(Umag) * handle->fullScaleVoltage_V * FIXP30_toF(Imag) * handle->fullScaleCurrent_A; if ((Imag > handle->Id_dc_ref_pu) || (Pmag > handle->PowerDC_goal_pu) || (handle->dc_duty_pu == handle->duty_maxgoal_pu)) { /* Current ramp-up complete. Actual duty in dc_duty_pu, prepare for the next phase */ if (handle->dc_duty_pu == handle->duty_maxgoal_pu) /* motor with high resistance and low current, use filtered values */ { handle->Id_dc_ref_pu = FIXP_mag(handle->IdqLP.D, handle->IdqLP.Q); } else { handle->Id_dc_ref_pu = FIXP_mag(Idq.D, Idq.Q); //make positive reference always } /* Set timer counter */ handle->counter = handle->measurement_counts; newState = PROFILER_DCAC_STATE_DC_Measuring; } } break; case PROFILER_DCAC_STATE_DC_Measuring: // if measurement time is done, save values and move on if (handle->counter == 0) { /* Calculate resistance value from filtered values */ fixp30_t Umag = FIXP_mag(handle->UdqLP.D, handle->UdqLP.Q); fixp30_t Imag = FIXP_mag(handle->IdqLP.D, handle->IdqLP.Q); if (Imag != 0) { handle->Rs_dc = (Umag * handle->fullScaleVoltage_V) / (Imag * handle->fullScaleCurrent_A); } handle->Umag_pu = Umag; handle->Imag_pu = Imag; handle->PowerDC_W = 1.5f * FIXP30_toF(Umag) * handle->fullScaleVoltage_V * FIXP30_toF(Imag) * handle->fullScaleCurrent_A; /* Start the AC measurement based on DC effective duty (keeping dead-time out of equation) */ float_t dutyDC = 2 * FIXP30_toF(handle->Umag_pu) / FIXP30_toF(motor->pVBus->Udcbus_in_pu); handle->ac_duty_pu = FIXP30(dutyDC * 0.5f); handle->counter = handle->measurement_counts; ZEST_setFreqInjectkHz(motor->pSPD->pZeST, handle->ac_freqkHz_pu); //inject AC frequency ZEST_setIdInject_pu(motor->pSPD->pZeST, handle->ac_duty_pu); //inject duty as if it was current... ZEST_setThresholdInjectActiveCurrent_A(motor->pSPD->pZeST, 0.0f); //remove threshold based on maxmotorcurrent newState = PROFILER_DCAC_STATE_AC_Measuring; } break; case PROFILER_DCAC_STATE_AC_Measuring: { if (handle->counter == 0) { handle->Rs_inject = ZEST_getR(motor->pSPD->pZeST); handle->Ls_inject = ZEST_getL(motor->pSPD->pZeST); fixp20_t Rsdc = FIXP20(handle->Rs_dc); fixp20_t Rsinject = FIXP20(handle->Rs_inject); fixp30_t Lsinject = FIXP30(handle->Ls_inject); /* Check AC and DC resistance to match */ if ((Rsinject < FIXP_mpy(Rsdc, FIXP(0.8f))) || (Rsinject > FIXP_mpy(Rsdc, FIXP(1.4f)))) { handle->error = PROFILER_DCAC_ERROR_ResistanceAC; } /* Check Ls: negative Ls can result at too low injection levels */ if (Lsinject <= FIXP(0.0f)) { handle->error = PROFILER_DCAC_ERROR_Inductance; } if (handle->error != PROFILER_DCAC_ERROR_None) { newState = PROFILER_DCAC_STATE_Error; } else { /* Set correct currentcontroller-parameters */ PIDREGDQX_CURRENT_setKpWiRLmargin_si(&motor->pCurrCtrl->pid_IdIqX_obj, handle->Rs_inject, handle->Ls_inject, 5.0f); /* Set correct ImpedanceCorrection-parameters */ PROFILER_DCAC_setImpedCorr_RsLs(handle, motor); ZEST_setIdInject_pu(motor->pSPD->pZeST, FIXP30(0.0f)); //stop injection. ZEST_setThresholdInjectActiveCurrent_A(motor->pSPD->pZeST, 0.02 * handle->Rs_dc); //set threshold to intended level if (handle->glue_dcac_fluxestim_on) { handle->counter = 20; newState = PROFILER_DCAC_STATE_DConly; } else { /* Start the ramp-down */ newState = PROFILER_DCAC_STATE_RampDown; } } } } break; case PROFILER_DCAC_STATE_DConly: if (handle->counter == 0) { newState = PROFILER_DCAC_STATE_Complete; } break; case PROFILER_DCAC_STATE_RampDown: // Reduce current reference by ramp rate if (handle->dc_duty_pu == FIXP30(0.0f)) { newState = PROFILER_DCAC_STATE_Complete; } break; case PROFILER_DCAC_STATE_Complete: /* No action */ break; case PROFILER_DCAC_STATE_Error: /* No action */ break; } if (state != newState) { handle->state = newState; } } /* Accessors */ /** * @brief todo */ float_t PROFILER_DCAC_getMeasurementTime(PROFILER_DCAC_Handle handle) { return handle->measurement_time_sec; } /** * @brief todo */ void PROFILER_DCAC_setIdDCMax(PROFILER_DCAC_Handle handle, const float_t id_dc_max) { handle->Id_dc_max_pu = FIXP30(id_dc_max / handle->fullScaleCurrent_A); } /** * @brief todo */ void PROFILER_DCAC_setImpedCorr_RsLs(PROFILER_DCAC_Handle handle, MOTOR_Handle motor) { { /* write estimated values of R and L to impedance correction */ IMPEDCORR_setRs_si(motor->pSPD->pImpedCorr, handle->Rs_dc); RSEST_setRsRatedOhm(motor->pSPD->pRsEst, handle->Rs_dc); IMPEDCORR_setLs_si(motor->pSPD->pImpedCorr, handle->Ls_inject); } { /* Set other inductance variables */ float_t Ls_pu_flt = handle->Ls_inject * handle->voltagefilterpole_rps * handle->fullScaleCurrent_A / handle->fullScaleVoltage_V; FIXPSCALED_floatToFIXPscaled(Ls_pu_flt, &motor->pFocVars->Ls_Rated_pu_fps); FIXPSCALED_floatToFIXPscaled(Ls_pu_flt, &motor->pSPD->Ls_Active_pu_fps); fixp24_t Ls_henry_fixp24 = FIXP24(handle->Ls_inject); motor->pFocVars->Ls_Rated_H = Ls_henry_fixp24; motor->pFocVars->Ls_Active_H = Ls_henry_fixp24; } } /** * @brief todo */ void PROFILER_DCAC_setMeasurementTime(PROFILER_DCAC_Handle handle, const float_t time_seconds) { handle->measurement_time_sec = time_seconds; handle->measurement_counts = (uint32_t) (time_seconds * handle->background_rate_hz); } /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
13,501
C
31.613526
146
0.660766
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/enc_align_ctrl.c
/** ****************************************************************************** * @file enc_align_ctrl.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of 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 */ /* Includes ------------------------------------------------------------------*/ #include "enc_align_ctrl.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @defgroup EncAlignCtrl Encoder Alignment Controller * @brief Encoder Alignment Controller component of the Motor Control SDK * * Initial encoder calibration which comprises a rotor alignment in a given position * necessary to make the information coming from a quadrature encoder absolute. * @{ */ /** * @brief It initializes the handle * @param pHandle: handler of the current instance of the EncAlignCtrl component. * @param pSTC: Pointer to Speed and Torque Controller structure used by the EAC. * @param pVSS: Pointer to Virtual Speed Sensor structure used by the EAC. * @param pENC: Pointer to ENCoder structure used by the EAC. */ __weak void EAC_Init(EncAlign_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC, VirtualSpeedSensor_Handle_t *pVSS, ENCODER_Handle_t *pENC) { #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->pSTC = pSTC; pHandle->pVSS = pVSS; pHandle->pENC = pENC; pHandle->EncAligned = false; pHandle->EncRestart = false; #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL } #endif } /** * @brief It starts the encoder alignment procedure. * It configures the VSS (Virtual Speed Sensor) with the required angle and sets the * STC (Speed and Torque Controller) to execute the required torque ramp. * @param pHandle: handler of the current instance of the EncAlignCtrl component. */ __weak void EAC_StartAlignment(EncAlign_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif uint32_t wAux; /* Set pVSS mechanical speed to zero */ VSS_SetMecAcceleration(pHandle->pVSS, 0, 0U); /* Set pVSS mechanical angle */ VSS_SetMecAngle(pHandle->pVSS, pHandle->hElAngle); /* Set pSTC in MCM_TORQUE_MODE */ STC_SetControlMode(pHandle->pSTC, MCM_TORQUE_MODE); /* Set starting torque to Zero */ (void)STC_ExecRamp(pHandle->pSTC, 0, 0U); /* Execute the torque ramp */ (void)STC_ExecRamp(pHandle->pSTC, pHandle->hFinalTorque, (uint32_t)pHandle->hDurationms); /* Compute hRemainingTicks, the number of thick of alignment phase */ wAux = ((uint32_t)pHandle->hDurationms) * ((uint32_t)pHandle->hEACFrequencyHz); wAux /= 1000U; pHandle->hRemainingTicks = (uint16_t)wAux; pHandle->hRemainingTicks++; #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL } #endif } /** * @brief It executes the encoder alignment controller and must be called with a * frequency equal to the one settled in the parameters * hEACFrequencyHz. Calling this method the EAC is able to verify * if the alignment duration has been finished. At the end of alignment * the encoder is set to the defined mechanical angle. * Note: STC and VSS are not called by EAC_Exec. * @param pHandle: handler of the current instance of the EncAlignCtrl component. * @retval bool It returns true when the programmed alignment has been * completed. */ __weak bool EAC_Exec(EncAlign_Handle_t *pHandle) { bool retVal = true; #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL if (NULL == pHandle) { retVal = false; } else { #endif if (pHandle->hRemainingTicks > 0U) { pHandle->hRemainingTicks--; if (0U == pHandle->hRemainingTicks) { /* At the end of Alignment procedure, we set the encoder mechanical angle to the alignement angle */ ENC_SetMecAngle(pHandle->pENC, pHandle->hElAngle / ((int16_t)pHandle->bElToMecRatio)); pHandle->EncAligned = true; retVal = true; } else { retVal = false; } } else { /* Nothing to do */ } #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL } #endif return (retVal); } /** * @brief It returns true if the encoder has been aligned at least * one time, false if hasn't been never aligned. * @param pHandle: handler of the current instance of the EncAlignCtrl component. * @retval bool Encoder Aligned flag */ __weak bool EAC_IsAligned(EncAlign_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13 { #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL return ((NULL == pHandle) ? false : pHandle->EncAligned); #else return (pHandle->EncAligned); #endif } /** * @brief It sets handler ENCrestart variable according to restart parameter * @param pHandle: handler of the current instance of the EncAlignCtrl component. * @param restart: Equal to true if a restart is programmed else false. */ __weak void EAC_SetRestartState(EncAlign_Handle_t *pHandle, bool restart) { #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->EncRestart = restart; #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL } #endif } /** * @brief Returns true if a restart after an encoder alignment has been requested. * @param pHandle: handler of the current instance of the EncAlignCtrl component. * @retval bool Encoder Alignment restart order flag */ __weak bool EAC_GetRestartState(EncAlign_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13 { #ifdef NULL_PTR_CHECK_ENC_ALI_CTRL return ((NULL == pHandle) ? false : pHandle->EncRestart); #else return (pHandle->EncRestart); #endif } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
6,473
C
28.972222
114
0.636336
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/r_divider_bus_voltage_sensor.c
/** ****************************************************************************** * @file r_divider_bus_voltage_sensor.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the Resistor Divider Bus Voltage Sensor 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 RDividerBusVoltageSensor */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "r_divider_bus_voltage_sensor.h" #include "regular_conversion_manager.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup BusVoltageSensor * @{ */ /** @defgroup RDividerBusVoltageSensor Resistor Divider Bus Voltage Sensor * @brief Resistor Divider Bus Voltage Sensor implementation. * * @{ */ /** * @brief It initializes bus voltage conversion (ADC, ADC channel, conversion time. It must be called only after PWM_Init. * @param pHandle related RDivider_Handle_t */ __weak void RVBS_Init(RDivider_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif /* Check */ RVBS_Clear(pHandle); #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS } #endif } /** * @brief It clears bus voltage FW variable containing average bus voltage * value. * @param pHandle related RDivider_Handle_t */ __weak void RVBS_Clear(RDivider_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif uint16_t aux; uint16_t index; aux = (pHandle->OverVoltageThreshold + pHandle->UnderVoltageThreshold) / 2U; for (index = 0U; index < pHandle->LowPassFilterBW; index++) { pHandle->aBuffer[index] = aux; } pHandle->_Super.LatestConv = aux; pHandle->_Super.AvBusVoltage_d = aux; pHandle->index = 0U; #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS } #endif } /** * @brief It actually performes the Vbus ADC conversion and updates averaged * value for all STM32 families except STM32F3 in u16Volt format. * @param pHandle related RDivider_Handle_t * @retval uint16_t Fault code error */ __weak uint16_t RVBS_CalcAvVbus(RDivider_Handle_t *pHandle, uint16_t rawValue) { uint16_t tempValue; #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS if (MC_NULL == pHandle) { tempValue = 0U; } else { #endif uint32_t wtemp; uint16_t hAux; uint8_t i; hAux = rawValue; if (0xFFFFU == hAux) { /* Nothing to do */ } else { /* Store latest value on buffer */ pHandle->aBuffer[pHandle->index] = hAux; wtemp = 0u; for (i = 0U; i < (uint8_t)pHandle->LowPassFilterBW; i++) { wtemp += pHandle->aBuffer[i]; } wtemp /= pHandle->LowPassFilterBW; /* Averaging done over the buffer stored values */ pHandle->_Super.AvBusVoltage_d = (uint16_t)wtemp; pHandle->_Super.LatestConv = hAux; if ((uint16_t)pHandle->index < (pHandle->LowPassFilterBW - 1U)) { pHandle->index++; } else { pHandle->index = 0U; } } pHandle->_Super.FaultState = RVBS_CheckFaultState(pHandle); tempValue = pHandle->_Super.FaultState; #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS } #endif return (tempValue); } /** * @brief It returns #MC_OVER_VOLT, #MC_UNDER_VOLT or #MC_NO_ERROR depending on * bus voltage and protection threshold values * @param pHandle related RDivider_Handle_t * @retval uint16_t Fault code error */ __weak uint16_t RVBS_CheckFaultState(RDivider_Handle_t *pHandle) { uint16_t fault; #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS if (MC_NULL == pHandle) { fault = MC_SW_ERROR; } else { #endif /* If both thresholds are equal, single threshold feature is used */ if (pHandle->OverVoltageThreshold == pHandle->OverVoltageThresholdLow) { if (pHandle->_Super.AvBusVoltage_d > pHandle->OverVoltageThreshold) { fault = MC_OVER_VOLT; } else if (pHandle->_Super.AvBusVoltage_d < pHandle->UnderVoltageThreshold) { fault = MC_UNDER_VOLT; } else { fault = MC_NO_ERROR; } } else { /* If both thresholds are different, hysteresis feature is used (Brake mode) */ if (pHandle->_Super.AvBusVoltage_d < pHandle->UnderVoltageThreshold) { fault = MC_UNDER_VOLT; } else if ( false == pHandle->OverVoltageHysteresisUpDir ) { if (pHandle->_Super.AvBusVoltage_d < pHandle->OverVoltageThresholdLow) { pHandle->OverVoltageHysteresisUpDir = true; fault = MC_NO_ERROR; } else{ fault = MC_OVER_VOLT; } } else { if (pHandle->_Super.AvBusVoltage_d > pHandle->OverVoltageThreshold) { pHandle->OverVoltageHysteresisUpDir = false; fault = MC_OVER_VOLT; } else{ fault = MC_NO_ERROR; } } } #ifdef NULL_PTR_CHECK_RDIV_BUS_VLT_SNS } #endif return (fault); } /** * @} */ /** * @} */ /** @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,846
C
23.464435
85
0.578857
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/current_ref_ctrl.c
/** ****************************************************************************** * @file current_ref_ctrl.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the * six-step current mode current reference PWM generation 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 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "current_ref_ctrl.h" /** @addtogroup MCSDK * @{ */ /** * @defgroup current_ref_ctrl Six-Step, current mode, PWM generation for current reference * * @brief PWM generation of the current reference for Six-Step drive with current mode * * This implementation exploits a timer to generate a PWM as reference to limit the current * peak by means an external comparator * * @{ */ /** * @brief It initializes TIMx * @param pHandle: handler of instance of the CRM component * @retval none */ __weak void CRM_Init(CurrentRef_Handle_t *pHandle) { switch (pHandle->pParams_str->RefTimerChannel) { case LL_TIM_CHANNEL_CH1: { LL_TIM_OC_SetCompareCH1(pHandle->pParams_str->TIMx, pHandle->StartCntPh); break; } case LL_TIM_CHANNEL_CH2: { LL_TIM_OC_SetCompareCH2(pHandle->pParams_str->TIMx, pHandle->StartCntPh); break; } case LL_TIM_CHANNEL_CH3: { LL_TIM_OC_SetCompareCH3(pHandle->pParams_str->TIMx, pHandle->StartCntPh); break; } case LL_TIM_CHANNEL_CH4: { LL_TIM_OC_SetCompareCH4(pHandle->pParams_str->TIMx, pHandle->StartCntPh); break; } default: { LL_TIM_OC_SetCompareCH1(pHandle->pParams_str->TIMx, pHandle->StartCntPh); break; } } LL_TIM_EnableCounter(pHandle->pParams_str->TIMx); LL_TIM_CC_EnableChannel(pHandle->pParams_str->TIMx, pHandle->pParams_str->RefTimerChannel); LL_TIM_EnableAllOutputs(pHandle->pParams_str->TIMx); } /** * @brief It clears TIMx counter and resets start-up duty cycle * @param pHandle: handler of instance of the CRM component * @retval none */ __weak void CRM_Clear(CurrentRef_Handle_t *pHandle) { LL_TIM_SetCounter(pHandle->pParams_str->TIMx, 0u); pHandle->Cnt = pHandle->StartCntPh; switch (pHandle->pParams_str->RefTimerChannel) { case LL_TIM_CHANNEL_CH1: { LL_TIM_OC_SetCompareCH1(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } case LL_TIM_CHANNEL_CH2: { LL_TIM_OC_SetCompareCH2(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } case LL_TIM_CHANNEL_CH3: { LL_TIM_OC_SetCompareCH3(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } case LL_TIM_CHANNEL_CH4: { LL_TIM_OC_SetCompareCH4(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } default: { LL_TIM_OC_SetCompareCH1(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } } } /** * @brief It updates current reference value * @param pHandle: handler of instance of the CRM component * @param hCnt: new reference value * @retval none */ __weak void CRM_SetReference(CurrentRef_Handle_t *pHandle, uint16_t hCnt) { pHandle->Cnt = hCnt; switch (pHandle->pParams_str->RefTimerChannel) { case LL_TIM_CHANNEL_CH1: { LL_TIM_OC_SetCompareCH1(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } case LL_TIM_CHANNEL_CH2: { LL_TIM_OC_SetCompareCH2(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } case LL_TIM_CHANNEL_CH3: { LL_TIM_OC_SetCompareCH3(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } case LL_TIM_CHANNEL_CH4: { LL_TIM_OC_SetCompareCH4(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } default: { LL_TIM_OC_SetCompareCH1(pHandle->pParams_str->TIMx, pHandle->Cnt); break; } } } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,564
C
24.361111
93
0.588738
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/bus_voltage_sensor.c
/** ****************************************************************************** * @file bus_voltage_sensor.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the BusVoltageSensor 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 BusVoltageSensor */ /* Includes ------------------------------------------------------------------*/ #include "bus_voltage_sensor.h" /** @addtogroup MCSDK * @{ */ /** @defgroup BusVoltageSensor Bus Voltage Sensing * @brief Bus Voltage Sensor components of the Motor Control SDK * * Two Bus Voltage Sensor implementations are provided (selection done according to BUS_VOLTAGE_READING definition): * * - The @ref RDividerBusVoltageSensor "Resistor Divider Bus Voltage Sensor" operates as the name suggests * - The @ref VirtualBusVoltageSensor "Virtual Bus Voltage Sensor" does not make measurement but rather * returns an application fixed defined value (expected VBus value). * * Two formats are used to return VBus measurement: * - Volt * - u16Volt that represents the ADC converted signal measuring the voltage at sensing network attenuation output * @f[ * u16Volt = (ADC\_REFERENCE\_VOLTAGE / VBUS\_PARTITIONING\_FACTOR) / 65536 * @f] * * @{ */ /** * @brief It return latest Vbus conversion result expressed in u16Volt format * @param pHandle related Handle of BusVoltageSensor_Handle_t * @retval uint16_t Latest Vbus conversion result in u16Volt format */ __weak uint16_t VBS_GetBusVoltage_d(const BusVoltageSensor_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_BUS_VOLT uint16_t temp_latestConv; if (MC_NULL == pHandle) { temp_latestConv = 0; } else { temp_latestConv = pHandle->LatestConv; } return (temp_latestConv); #else return (pHandle->LatestConv); #endif } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief It return latest averaged Vbus measurement expressed in u16Volt format * @param pHandle related Handle of BusVoltageSensor_Handle_t * @retval uint16_t Latest averaged Vbus measurement in u16Volt format */ __weak uint16_t VBS_GetAvBusVoltage_d(const BusVoltageSensor_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_BUS_VOLT uint16_t temp_avBusVoltage_d; if (MC_NULL == pHandle) { temp_avBusVoltage_d = 0U; } else { temp_avBusVoltage_d = pHandle->AvBusVoltage_d; } return (temp_avBusVoltage_d); #else return (pHandle->AvBusVoltage_d); #endif } /** * @brief It return latest averaged Vbus measurement expressed in Volt format * @param pHandle related Handle of BusVoltageSensor_Handle_t * @retval uint16_t Latest averaged Vbus measurement in Volt format */ __weak uint16_t VBS_GetAvBusVoltage_V(const BusVoltageSensor_Handle_t *pHandle) { uint32_t temp; #ifdef NULL_PTR_CHECK_BUS_VOLT if (MC_NULL == pHandle) { temp = 0U; } else { #endif temp = (uint32_t)(pHandle->AvBusVoltage_d); temp *= pHandle->ConversionFactor; temp /= 65536U; #ifdef NULL_PTR_CHECK_BUS_VOLT } #endif return ((uint16_t)temp); } /** * @brief It returns #MC_OVER_VOLT, #MC_UNDER_VOLT or #MC_NO_ERROR depending on * bus voltage and protection threshold values * @param pHandle related Handle of BusVoltageSensor_Handle_t * @retval uint16_t Fault code error */ __weak uint16_t VBS_CheckVbus(const BusVoltageSensor_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_BUS_VOLT uint16_t temp_faultState; if (MC_NULL == pHandle) { temp_faultState = 0U; } else { temp_faultState = pHandle->FaultState; } return (temp_faultState); #else return (pHandle->FaultState); #endif } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,512
C
26.351515
117
0.636082
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/pwm_curr_fdbk_ovm.c
/** ****************************************************************************** * @file pwm_curr_fdbk_ovm.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the following features * of the PWM & Current Feedback component of the Motor Control SDK: * * * current sensing * * regular ADC conversion execution * * space vector modulation * ****************************************************************************** * @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 pwm_curr_fdbk */ /* Includes ------------------------------------------------------------------*/ #include "pwm_curr_fdbk.h" #include "mc_math.h" #include "mc_type.h" /* Private defines ------------------------------------------------------------*/ /* @brief The float number 1.0 equal to 32768 ; represents the vector from center to an angle of the hexagon. */ #define OVM_ONE_POINT_ZERO ((int32_t)32768) #define OVM_GAIN_ARRAY_SIZE ((int32_t)192) #define OVM_GAMMA_ARRAY_SIZE ((int32_t)100) #define OVM_GAMMA_ARRAY_OFFSET ((int32_t)92) #define OVM_VREF_MODE1_START ((int32_t)29717) #define OVM_VREF_MODE2_START ((int32_t)31186) #define OVM_VREF_MODE2_END ((int32_t)32768) #define OVM_VREF_INDEX_STEP ((int32_t)16) #define OVM_1_DIV_SQRT3 ((int32_t)18919) #define OVM_1_DIV_PI ((int32_t)10430) #define OVM_PI_DIV_6 ((int32_t)17157) #define OVM_3_DIV_PI ((int32_t)31291) #define OVM_SQRT3 ((int32_t)56754) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * * @{ */ /* Private variables ----------------------------------------------------------*/ /** * @brief Vector modules T1 and T2. Specified in @ref overmodulation.md */ typedef struct { int32_t T1; int32_t T2; } Vector_Time_t; /** * @brief Overmodulation modes. Specified in @ref overmodulation.md */ typedef enum { OVM_LINEAR = 0, /**< Linear mode. */ OVM_1 = 1, /**< Overmodulation mode 1. */ OVM_2 = 2, /**< Overmodulation mode 2. */ OVM_ERROR = 3 /**< Error output. */ } OVM_Mode_t; /** * @} */ /** * @} */ /* Private function prototypes -----------------------------------------------*/ static Vector_Time_t PWMC_RecalcT1T2_OVM(Vector_Time_t time, OVM_Mode_t mode, int16_t gamma); #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /* * @brief Recalculates vectors T1 and T2 stored in @p time structure, * depending on the overmodulation @p mode and @p gamma gain. * * @retval New values of T1 & T2. */ static Vector_Time_t PWMC_RecalcT1T2_OVM(Vector_Time_t time, OVM_Mode_t mode, int16_t gamma) { int32_t sum_t1_t2; int32_t offset; int32_t gain; int32_t t1_temp; Vector_Time_t time_prime; time_prime.T1 = 0; time_prime.T2 = 0; if ((OVM_LINEAR == mode) || (OVM_1 == mode)) { sum_t1_t2 = time.T1 + time.T2; if (sum_t1_t2 > OVM_ONE_POINT_ZERO) { time_prime.T1 = ((time.T1 * OVM_ONE_POINT_ZERO) / sum_t1_t2); time_prime.T2 = OVM_ONE_POINT_ZERO - time_prime.T1; } else { time_prime.T1 = time.T1; time_prime.T2 = time.T2; } } else if (OVM_2 == mode) { if (time.T1 > OVM_ONE_POINT_ZERO) { time_prime.T1 = OVM_ONE_POINT_ZERO; time_prime.T2 = 0; } else if (time.T2 > OVM_ONE_POINT_ZERO) { time_prime.T1 = 0; time_prime.T2 = OVM_ONE_POINT_ZERO; } else { offset = (OVM_3_DIV_PI * gamma) / OVM_ONE_POINT_ZERO; gain = (OVM_PI_DIV_6 * OVM_ONE_POINT_ZERO) / (OVM_PI_DIV_6 - gamma); sum_t1_t2 = time.T1 + time.T2; sum_t1_t2 = ((0 == sum_t1_t2) ? 1 : sum_t1_t2); t1_temp = (time.T1 * OVM_ONE_POINT_ZERO) / sum_t1_t2; t1_temp = t1_temp - offset; if (t1_temp < 0) { t1_temp = 0; } else { /* Nothing to do */ } if (gain > OVM_ONE_POINT_ZERO) { gain = gain / OVM_ONE_POINT_ZERO; time_prime.T1 = t1_temp * gain; } else { time_prime.T1 = (t1_temp * gain) / OVM_ONE_POINT_ZERO; } if (time_prime.T1 > OVM_ONE_POINT_ZERO) { time_prime.T1 = OVM_ONE_POINT_ZERO; } else { /* Nothing to do */ } time_prime.T2 = OVM_ONE_POINT_ZERO - time_prime.T1; } } else /* Error mode output 0 to protect */ { time_prime.T1 = 0; time_prime.T2 = 0; } return (time_prime); } /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * * @{ */ #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Converts input voltage components @f$ V_{\alpha} @f$ and @f$ V_{\beta} @f$ into duty cycles * and feeds them to the inverter with overmodulation function. * * @param pHandle: Handler of the current instance of the PWM component. * @param Valfa_beta: Voltage Components expressed in the @f$(\alpha, \beta)@f$ reference frame. * @retval #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 PWMC_SetPhaseVoltage_OVM(PWMC_Handle_t *pHandle, alphabeta_t Valfa_beta) { /* Private variables ----------------------------------------------------------*/ /* Overmodulation gain array */ static const uint16_t aOVMGain[OVM_GAIN_ARRAY_SIZE]={\ 31291,31291,31293,31295,31298,31300,31302,31306,31309,31314,\ 31319,31322,31328,31334,31338,31344,31350,31357,31364,31371,\ 31379,31386,31394,31402,31410,31419,31427,31439,31448,31457,\ 31470,31479,31492,31502,31515,31526,31539,31554,31568,31579,\ 31594,31609,31624,31639,31655,31675,31691,31707,31728,31745,\ 31766,31783,31805,31827,31845,31868,31891,31914,31942,31966,\ 31990,32019,32044,32074,32104,32134,32165,32202,32233,32271,\ 32303,32341,32386,32425,32470,32516,32562,32609,32662,32716,\ 32777,32838,32907,32982,33059,33144,33236,33343,33466,33612,\ 33797,34106,34463,34507,34551,34596,34640,34684,34729,34779,\ 34824,34869,34920,34971,35017,35068,35120,35178,35230,35282,\ 35340,35392,35451,35509,35568,35627,35686,35752,35811,35877,\ 35943,36009,36075,36148,36214,36287,36360,36434,36507,36581,\ 36661,36742,36822,36903,36990,37078,37159,37253,37342,37436,\ 37531,37627,37729,37831,37933,38042,38152,38261,38378,38495,\ 38612,38736,38860,38991,39122,39261,39399,39545,39691,39844,\ 40004,40165,40332,40507,40682,40871,41061,41264,41469,41680,\ 41906,42139,42387,42649,42911,43188,43488,43801,44137,44487,\ 44866,45275,45713,46195,46715,47300,47958,48720,49629,50759,\ 52346,56660,\ }; /* Overmodulation gamma array */ static const int16_t aOVMGamma[OVM_GAMMA_ARRAY_SIZE]={\ 52,154,255,354,453,551,648,757,852,947,\ 1052,1157,1249,1352,1454,1566,1666,1765,1875,1972,\ 2079,2186,2291,2395,2499,2612,2713,2824,2934,3042,\ 3150,3266,3372,3486,3599,3711,3821,3931,4049,4166,\ 4281,4395,4517,4637,4748,4875,4992,5115,5238,5359,\ 5487,5614,5739,5870,6000,6129,6263,6396,6528,6665,\ 6800,6941,7080,7224,7367,7514,7659,7809,7963,8115,\ 8272,8432,8590,8757,8922,9096,9268,9442,9624,9809,\ 10001,10200,10395,10597,10810,11028,11255,11487,11731,11987,\ 12254,12539,12835,13158,13507,13895,14335,14853,15530,17125,\ }; uint16_t retvalue; #ifdef NULL_PTR_CHECK_PWM_CUR_FDB_OVM if (NULL == pHandle) { retvalue = 0U; } else { #endif int32_t wX; int32_t wY; int32_t wZ; int32_t wUAlpha; int32_t wUBeta; int32_t vref; int32_t gain; int32_t neg_beta_cmd_div_sqrt3; int32_t duty_a; int32_t duty_b; int32_t duty_c; int32_t gama = 0; int16_t index; OVM_Mode_t ovm_mode_flag; Vector_Time_t vector_time; /* Transfer vref to vcmd */ vref = (int32_t)MCM_Modulus( Valfa_beta.alpha, Valfa_beta.beta ); if (vref < OVM_VREF_MODE1_START) /* Linear range */ { wUAlpha = Valfa_beta.alpha; wUBeta = Valfa_beta.beta; ovm_mode_flag = OVM_LINEAR; } else if (vref < OVM_VREF_MODE2_START) /* OVM mode 1 range */ { index = (int16_t)((vref - OVM_VREF_MODE1_START) / OVM_VREF_INDEX_STEP); gain = (int32_t)aOVMGain[index]; wUAlpha = (Valfa_beta.alpha * gain) / OVM_ONE_POINT_ZERO; wUBeta = (Valfa_beta.beta * gain) / OVM_ONE_POINT_ZERO; ovm_mode_flag = OVM_1; } else if (vref < OVM_VREF_MODE2_END) /* OVM mode 2 range */ { index = (int16_t)((vref - OVM_VREF_MODE1_START) / OVM_VREF_INDEX_STEP); gain = (int32_t)aOVMGain[index]; wUAlpha = (Valfa_beta.alpha * gain) / OVM_ONE_POINT_ZERO; wUBeta = (Valfa_beta.beta * gain) / OVM_ONE_POINT_ZERO; if (index > OVM_GAMMA_ARRAY_OFFSET) { gama = aOVMGamma[index - OVM_GAMMA_ARRAY_OFFSET]; } else { gama = aOVMGamma[0]; } ovm_mode_flag = OVM_2; } else /* Out of OVM mode 2 range only a protection to prevent the code to a undefined branch */ { wUAlpha = 0; wUBeta = 0; ovm_mode_flag = OVM_ERROR; } /* Vcmd to X, Y, Z */ neg_beta_cmd_div_sqrt3 = ((-wUBeta) * OVM_1_DIV_SQRT3) / OVM_ONE_POINT_ZERO; wX = neg_beta_cmd_div_sqrt3 * 2; /* x=-(2/sqrt(3))*beta */ wY = wUAlpha + neg_beta_cmd_div_sqrt3; /* x=alpha-(1/sqrt(3))*beta */ wZ = -wUAlpha + neg_beta_cmd_div_sqrt3;; /* x=-alpha-(1/sqrt(3))*beta */ /* Sector calculation from wX, wY, wZ */ if (wY < 0) { if (wZ < 0) { pHandle->Sector = SECTOR_5; vector_time.T1 = -wY; vector_time.T2 = -wZ; vector_time = PWMC_RecalcT1T2_OVM( vector_time, ovm_mode_flag, (int16_t)gama ); duty_a = 16384 + ((-vector_time.T1 + vector_time.T2) / 2); #ifndef FULL_MISRA_C_COMPLIANCY_PW_CURR_FDB_OVM //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) >> 16; duty_b = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) >> 16; duty_c = 16384 + ((vector_time.T1 + vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) >> 16; #else duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) / 65536; duty_b = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) / 65536; duty_c = 16384 + ((vector_time.T1 + vector_time.T2) / 2); duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) / 65536; #endif pHandle->lowDuty = (uint16_t)duty_c; pHandle->midDuty = (uint16_t)duty_a; pHandle->highDuty = (uint16_t)duty_b; } else /* wZ >= 0 */ if (wX <= 0) { pHandle->Sector = SECTOR_4; vector_time.T1 = wZ; vector_time.T2 = -wX; vector_time = PWMC_RecalcT1T2_OVM( vector_time, ovm_mode_flag, (int16_t)gama ); duty_a = 16384 + ((- vector_time.T1 - vector_time.T2) / 2); #ifndef FULL_MISRA_C_COMPLIANCY_PW_CURR_FDB_OVM //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) >> 16; duty_b = 16384 + ((vector_time.T1 - vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) >> 16; duty_c = 16384 + ((vector_time.T1 + vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) >> 16; #else duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) / 65536; duty_b = 16384 + ((vector_time.T1 - vector_time.T2) / 2); duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) / 65536; duty_c = 16384 + ((vector_time.T1 + vector_time.T2) / 2); duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) / 65536; #endif pHandle->lowDuty = (uint16_t)duty_c; pHandle->midDuty = (uint16_t)duty_b; pHandle->highDuty = (uint16_t)duty_a; } else /* wX > 0 */ { pHandle->Sector = SECTOR_3; vector_time.T1 = wX; vector_time.T2 = -wY; vector_time = PWMC_RecalcT1T2_OVM( vector_time, ovm_mode_flag, (int16_t)gama ); duty_a = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); #ifndef FULL_MISRA_C_COMPLIANCY_PW_CURR_FDB_OVM //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) >> 16; duty_b = 16384 + ((vector_time.T1 + vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) >> 16; duty_c = 16384 + ((- vector_time.T1 + vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) >> 16; #else duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) / 65536; duty_b = 16384 + ((vector_time.T1 + vector_time.T2) / 2); duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) / 65536; duty_c = 16384 + ((- vector_time.T1 + vector_time.T2) / 2); duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) / 65536; #endif pHandle->lowDuty = (uint16_t)duty_b; pHandle->midDuty = (uint16_t)duty_c; pHandle->highDuty = (uint16_t)duty_a; } } else /* wY > 0 */ { if (wZ >= 0) { pHandle->Sector = SECTOR_2; vector_time.T1 = wY; vector_time.T2 = wZ; vector_time = PWMC_RecalcT1T2_OVM( vector_time, ovm_mode_flag, (int16_t)gama); duty_a = 16384 + ((vector_time.T1 - vector_time.T2) / 2); #ifndef FULL_MISRA_C_COMPLIANCY_PW_CURR_FDB_OVM //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) >> 16; duty_b = 16384 + ((vector_time.T1 + vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) >> 16; duty_c = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) >> 16; #else duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) / 65536; duty_b = 16384 + ((vector_time.T1 + vector_time.T2) / 2); duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) / 65536; duty_c = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) / 65536; #endif pHandle->lowDuty = (uint16_t)duty_b; pHandle->midDuty = (uint16_t)duty_a; pHandle->highDuty = (uint16_t)duty_c; } else /* wZ < 0 */ if (wX <= 0) { pHandle->Sector = SECTOR_6; vector_time.T1 = -wX; vector_time.T2 = wY; vector_time = PWMC_RecalcT1T2_OVM( vector_time, ovm_mode_flag, (int16_t)gama); duty_a = 16384 + ((vector_time.T1 + vector_time.T2) / 2); #ifndef FULL_MISRA_C_COMPLIANCY_PW_CURR_FDB_OVM //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) >> 16; duty_b = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) >> 16; duty_c = 16384 + ((vector_time.T1 - vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) >> 16; #else duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) / 65536; duty_b = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) / 65536; duty_c = 16384 + ((vector_time.T1 - vector_time.T2) / 2); duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) / 65536; #endif pHandle->lowDuty = (uint16_t)duty_a; pHandle->midDuty = (uint16_t)duty_c; pHandle->highDuty = (uint16_t)duty_b; } else /* wX > 0 */ { pHandle->Sector = SECTOR_1; vector_time.T1 = -wZ; vector_time.T2 = wX; vector_time = PWMC_RecalcT1T2_OVM( vector_time, ovm_mode_flag, (int16_t)gama); duty_a = 16384 + ((vector_time.T1 + vector_time.T2) / 2); #ifndef FULL_MISRA_C_COMPLIANCY_PW_CURR_FDB_OVM //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) >> 16; duty_b = 16384 + ((-vector_time.T1 + vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) >> 16; duty_c = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) >> 16; #else duty_a = (((int32_t)pHandle->PWMperiod) * duty_a) / 65536; duty_b = 16384 + ((-vector_time.T1 + vector_time.T2) / 2); duty_b = (((int32_t)pHandle->PWMperiod) * duty_b) / 65536; duty_c = 16384 + ((-vector_time.T1 - vector_time.T2) / 2); duty_c = (((int32_t)pHandle->PWMperiod) * duty_c) / 65536; #endif pHandle->lowDuty = (uint16_t)duty_a; pHandle->midDuty = (uint16_t)duty_b; pHandle->highDuty = (uint16_t)duty_c; } } pHandle->CntPhA = (uint16_t)duty_a ; pHandle->CntPhB = (uint16_t)duty_b ; pHandle->CntPhC = (uint16_t)duty_c; retvalue = pHandle->pFctSetADCSampPointSectX(pHandle); #ifdef NULL_PTR_CHECK_PWM_CUR_FDB_OVM } #endif return (retvalue); } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
19,199
C
35.852207
112
0.567634
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/speed_regulator_potentiometer.c
/** ****************************************************************************** * @file speed_regulator_potentiometer.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of 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 */ /* Includes ------------------------------------------------------------------*/ #include "speed_regulator_potentiometer.h" /** @addtogroup MCSDK * @{ */ /** * @defgroup SpeedRegulatorPotentiometer Speed Potentiometer * @brief Potentiometer for motor speed reference setting compotent of the Motor Control SDK. * * Reads a potentiometer and sets the mechanical speed reference of the rotor accordingly. * * The Speed Regulator Potentiometer component reads a potentiometer thro. * * @todo Complete the documentation of the Speed Regulator Potentiometer component. * * @{ */ /* Functions ---------------------------------------------------- */ /** * @brief Initializes a Speed Regulator Potentiometer component. * * @param pHandle The Speed Regulator Potentiometer component to initialize. * */ __weak void SRP_Init(SRP_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pSTC) { #ifdef NULL_PTR_CHECK_SPD_REG_POT if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif /* Need to be register with RegularConvManager */ pHandle->convHandle = RCM_RegisterRegConv(&pHandle->SpeedRegConv); pHandle->pSTC = pSTC; SRP_Clear(pHandle); #ifdef NULL_PTR_CHECK_SPD_REG_POT } #endif } /** * @brief Resets the internal state of a Speed Regulator Potentiometer component. * * @param pHandle Handle of the Speed Regulator Potentiometer component. */ __weak void SRP_Clear(SRP_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_SPD_REG_POT if (MC_NULL == pHandle) { /* nothing to do */ } else { #endif uint16_t aux; uint16_t index; aux = (pHandle->MaximumSpeedRange + pHandle->MinimumSpeedRange) / 2u; for (index = 0u; index < pHandle->LowPassFilterBW; index++) { pHandle->aBuffer[index] = aux; } pHandle->LatestConv = aux; pHandle->AvSpeedReg_d = aux; pHandle->index = 0; #ifdef NULL_PTR_CHECK_SPD_REG_POT } #endif } /** * @brief * * @param pHandle * @return uint16_t */ static uint16_t SRP_ConvertSpeedRegFiltered(SRP_Handle_t *pHandle, uint16_t rawValue) { uint16_t hAux; uint8_t vindex; uint16_t max = 0, min = 0; uint32_t tot = 0u; for (vindex = 0; vindex < pHandle->LowPassFilterBW;) { hAux = rawValue; if (hAux != 0xFFFFu) { if (vindex == 0) { min = hAux; max = hAux; } else { if (hAux < min) { min = hAux; } if (hAux > max) { max = hAux; } } vindex++; tot += hAux; } } tot -= max; tot -= min; return ((uint16_t)(tot / (pHandle->LowPassFilterBW - 2u))); } /** * @brief * * @param pHandle * @param DigitValue * @return uint16_t */ static inlineuint16_t SRP_SpeedDigitToSpeedUnit(SRP_Handle_t *pHandle, uint16_t DigitValue) { uint16_t hAux; hAux = (DigitValue / pHandle->ConversionFactor) + pHandle->MinimumSpeedRange; return (hAux); } /** * @brief * * @param pHandle * @param SpeedUnitValue * @return uint16_t */ static uint16_t SRP_SpeedUnitToSpeedDigit(SRP_Handle_t *pHandle, int16_t SpeedUnitValue) { uint16_t hAux = 0; if (SpeedUnitValue < 0) { SpeedUnitValue = -SpeedUnitValue; } else { /* Nothing to do */ } if (SpeedUnitValue > pHandle->MinimumSpeedRange) { hAux = (SpeedUnitValue - pHandle->MinimumSpeedRange) * pHandle->ConversionFactor; } else { /* Nothing to do */ } return (hAux); } /** * @brief Reads the potentiometer of an SRP component and filters it to compute an average speed reference. * * It actually performes the Speed regulator ADC conversion and updates average value. * @param pHandle related SRP_Handle_t. * @retval bool OutOfSynch signal. */ __weak bool SRP_CalcAvSpeedRegFilt(SRP_Handle_t *pHandle, uint16_t rawValue) { uint32_t wtemp; uint16_t hAux; uint8_t i; hAux = SRP_ConvertSpeedRegFiltered(pHandle, rawValue); if (hAux != 0xFFFF) { pHandle->aBuffer[pHandle->index] = hAux; wtemp = 0; for (i = 0; i < pHandle->LowPassFilterBW; i++) { wtemp += pHandle->aBuffer[i]; } wtemp /= pHandle->LowPassFilterBW; pHandle->AvSpeedReg_d = (uint16_t)wtemp; pHandle->LatestConv = hAux; if (pHandle->index < (pHandle->LowPassFilterBW - 1)) { pHandle->index++; } else { pHandle->index = 0; } } else { /* Nothing to do */ } pHandle->OutOfSynchro = SRP_CheckSpeedRegSync(pHandle); return (pHandle->OutOfSynchro); } #ifdef NOT_IMPLEMENTED /** * @brief It actually performes the speed regulator ADC conversion and updates average value. * @param pHandle related SRP_Handle_t. * @retval bool OutOfSynch signal. */ __weak bool SRP_CalcAvSpeedReg(SRP_Handle_t * pHandle) { uint32_t wtemp; uint16_t hAux; uint8_t i; hAux = RCM_ExecRegularConv(pHandle->convHandle); if (hAux != 0xFFFF) { pHandle->aBuffer[pHandle->index] = hAux; wtemp = 0; for (i = 0; i < pHandle->LowPassFilterBW; i++) { wtemp += pHandle->aBuffer[i]; } wtemp /= pHandle->LowPassFilterBW; pHandle->AvSpeedReg_d = (uint16_t)wtemp; pHandle->LatestConv = hAux; if (pHandle->index < pHandle->LowPassFilterBW - 1) { pHandle->index++; } else { pHandle->index = 0; } } pHandle->OutOfSynchro = SRP_CheckSpeedRegSync(pHandle); return (pHandle->OutOfSynchro); } #endif __weak bool SRP_CalcAvgSpeedReg(void) { uint32_t wtemp; uint16_t hAux; uint8_t i; /* Check regular conversion state */ if (RCM_GetUserConvState() == RCM_USERCONV_IDLE) { /* If Idle, then program a new conversion request */ RCM_RequestUserConv(handle); } else if (RCM_GetUserConvState() == RCM_USERCONV_EOC) { /* If completed, then read the captured value */ hAux = RCM_GetUserConv(); if (hAux != 0xFFFF) { pHandle->aBuffer[pHandle->index] = hAux; wtemp = 0; for (i = 0; i < pHandle->LowPassFilterBW; i++) { wtemp += pHandle->aBuffer[i]; } wtemp /= pHandle->LowPassFilterBW; pHandle->AvSpeedReg_d = (uint16_t)wtemp; pHandle->LatestConv = hAux; if (pHandle->index < pHandle->LowPassFilterBW - 1) { pHandle->index++; } else { pHandle->index = 0; } } else { /* Nothing to do */ } } pHandle->OutOfSynchro = SRP_CheckSpeedRegSync(pHandle); return (pHandle->OutOfSynchro); } /** * @brief It returns OutOfSync check between current potentiometer setting and measured speed. * @param pHandle related SRP_Handle_t. * @retval bool OutOfSynch signal. */ __weak bool SRP_CheckSpeedRegSync(SRP_Handle_t *pHandle) { uint16_t speedRegValue = SRP_SpeedDigitToSpeedUnit(pHandle, pHandle->AvSpeedReg_d); uint16_t speedRegTol = SRP_SpeedDigitToSpeedUnit(pHandle, pHandle->SpeedAdjustmentRange); SpeednPosFdbk_Handle_t *speedHandle; bool hAux = false; speedHandle = STC_GetSpeedSensor(pHandle->pSTC); if ((speedHandle->hAvrMecSpeedUnit > (speedRegValue + speedRegTol)) || (speedHandle->hAvrMecSpeedUnit < (speedRegValue - speedRegTol))) { hAux = true; } else { /* Nothing to do */ } return (hAux); } /** * @brief Executes speed ramp and applies external speed regulator new setpoint if ajustment range is violated * @param pHandle related SRP_Handle_t * @retval bool final speed is equal to measured speed */ __weak bool SRP_ExecPotRamp(SRP_Handle_t *pHandle) { bool hAux = SRP_CheckSpeedRegSync(pHandle); uint16_t PotentiometerReqSpeed = pHandle->LatestConv; uint16_t PotentiometerCurrentSpeed = pHandle->AvSpeedReg_d; SpeednPosFdbk_Handle_t *speedHandle; speedHandle = STC_GetSpeedSensor(pHandle->pSTC); int16_t CurrentSpeed = speedHandle->hAvrMecSpeedUnit; /* Requested speed must be different from previous one */ if ((PotentiometerReqSpeed <= PotentiometerCurrentSpeed - pHandle->SpeedAdjustmentRange) | (PotentiometerReqSpeed >= PotentiometerCurrentSpeed + pHandle->SpeedAdjustmentRange)) { uint32_t hDuration; int16_t deltaSpeed; uint16_t RequestedSpeed = SRP_SpeedDigitToSpeedUnit(pHandle, PotentiometerReqSpeed); deltaSpeed = (int16_t) RequestedSpeed - CurrentSpeed; if (deltaSpeed > 0) { hDuration = (((uint32_t)deltaSpeed) * 1000) / pHandle->RampSlope; } else { hDuration = (((uint32_t)(- deltaSpeed)) * 1000) / pHandle->RampSlope; } if (CurrentSpeed < 0) { STC_ExecRamp(pHandle->pSTC, (int16_t)(- RequestedSpeed), hDuration); } else { STC_ExecRamp(pHandle->pSTC, (int16_t)RequestedSpeed, hDuration); } } return (hAux); } /** * @brief Returns the latest value read from the potentiometer of a Speed Regulator Potentiometer component * * @param pHandle Handle of the Speed Regulator Potentiometer component */ __weak uint16_t SRP_GetSpeedReg_d(SRP_Handle_t *pHandle) { return (pHandle->LatestConv); } /** * @brief Returns the speed reference computed by a Speed Regulator Potentiometer * component expressed in u16digits. * * This speed reference is an average computed over the last values read from the potentiometer. * * The number of values on which the average is computed is given by SRP_Handle_t::LowPassFilterBW. * * @param pHandle Handle of the Speed Regulator Potentiometer component */ __weak uint16_t SRP_GetAvSpeedReg_d(SRP_Handle_t *pHandle) { return (pHandle->AvSpeedReg_d); } /** * @brief Returns the speed reference computed by a Speed Regulator Potentiometer component * expressed in #SPEED_UNIT * * @param pHandle Handle of the Speed Regulator Potentiometer component */ __weak uint16_t SRP_GetAvSpeedReg_SU(SRP_Handle_t *pHandle) { uint16_t temp = SRP_SpeedDigitToSpeedUnit(pHandle, pHandle->AvSpeedReg_d); return (temp); } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
10,976
C
23.722973
112
0.630102
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/datalog.c
/** ****************************************************************************** * @file datalog.c * @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.c */ #include "datalog.h" #include <string.h> // memset bool DATALOG_checkTrigger(DATALOG_Handle handle); void DATALOG_clearChannelData(DATALOG_Handle handle, int channel); void DATALOG_setSampleWindow(DATALOG_Handle handle); DATALOG_Handle DATALOG_init(void* pMemory, const size_t numBytes) { DATALOG_Handle handle = (DATALOG_Handle) NULL; if (numBytes >= sizeof(DATALOG_Obj)) /* Size was mismatched once - Are dependancies to .h files being checked correctly? */ { handle = (DATALOG_Handle) pMemory; memset(pMemory, 0, numBytes); } return (handle); } /* end of DATALOG_init() function */ void DATALOG_setup(DATALOG_Handle handle) { DATALOG_Obj* obj = handle; int channel; for (channel = 0; channel < DATALOG_NUM_CHANNELS; channel++) { DATALOG_CHANNEL_s* pChannel = &handle->channel[channel]; pChannel->bEnabled = false; pChannel->pSource = (void*) NULL; DATALOG_clearChannelData(handle, channel); } obj->nextSampleIdx = 0; obj->endSampleIdx = 0; obj->dataStartIdx = 0; obj->triggerIdx = 0; obj->bClear = false; obj->bArmTrigger = false; obj->bClearHold = false; obj->trigger.channel = 0; obj->trigger.level = 16384; obj->trigger.mode = DATALOG_TRIGGER_MODE_Normal; obj->trigger.state = DATALOG_TRIGGER_STATE_Idle; obj->trigger.edge = DATALOG_TRIGGER_EDGE_DIRECTION_Rising; obj->trigger.preTrigger = 1; obj->state = DATALOG_STATE_Idle; obj->command = DATALOG_COMMAND_None; obj->downsample = 3; obj->downsamplecounter = 0; } /* end of DATALOG_setup() function */ void DATALOG_run(DATALOG_Handle handle) { DATALOG_Obj* obj = handle; /* Debug control of scope */ if (obj->bClearHold) { if (obj->trigger.state == DATALOG_TRIGGER_STATE_Holding) { obj->trigger.state = DATALOG_TRIGGER_STATE_Idle; } obj->bClearHold = false; } if (obj->bArmTrigger) { obj->trigger.state = DATALOG_TRIGGER_STATE_Armed; obj->channel[obj->trigger.channel].lastSample = 0; obj->channel[obj->trigger.channel].currentSample = 0; obj->bArmTrigger = false; obj->trigger.justArmed = true; } if (obj->bClear) { int channel; for (channel = 0; channel < DATALOG_NUM_CHANNELS; channel++) { DATALOG_clearChannelData(handle, channel); } obj->bClear = false; } switch (obj->command) { case DATALOG_COMMAND_None: break; case DATALOG_COMMAND_Arm: // Only when holding or idle /* Whatever the current state, reset and re-arm the trigger */ if (obj->trigger.state == DATALOG_TRIGGER_STATE_Idle || obj->trigger.state == DATALOG_TRIGGER_STATE_Holding) { obj->trigger.state = DATALOG_TRIGGER_STATE_Armed; obj->channel[obj->trigger.channel].lastSample = 0; obj->channel[obj->trigger.channel].currentSample = 0; obj->state = DATALOG_STATE_Armed; obj->trigger.justArmed = true; } break; case DATALOG_COMMAND_Stop: break; } /* Clear the command */ obj->command = DATALOG_COMMAND_None; /* Scope functionality */ if (obj->trigger.mode == DATALOG_TRIGGER_MODE_Normal) { uint16_t nextSampleIdx = obj->nextSampleIdx; DATALOG_TRIGGER_STATE_e triggerState = obj->trigger.state; if (triggerState == DATALOG_TRIGGER_STATE_Holding) { // No capture during holding return; } if (triggerState == DATALOG_TRIGGER_STATE_Armed) { /* While armed, we need to update the triggering channel values, or we won't see the trigger */ DATALOG_CHANNEL_s* pChannel = &obj->channel[obj->trigger.channel]; if (pChannel->bEnabled) { DATALOG_SAMPLE_TYPE sample = *((DATALOG_SAMPLE_TYPE*) pChannel->pSource); pChannel->lastSample = pChannel->currentSample; pChannel->currentSample = sample; } // Check for trigger if (DATALOG_checkTrigger(handle)) { #ifdef SUPPORT_PRETRIGGER_AND_WRAPPED_DATA /* Can only be used if the client supports unwrapping the data */ // Trigger fired, determine end of log DATALOG_setSampleWindow(handle); obj->triggerIdx = nextSampleIdx; obj->trigger.state = DATALOG_TRIGGER_STATE_Running; obj->state = DATALOG_STATE_Running; #else /* SUPPORT_PRETRIGGER_AND_WRAPPED_DATA */ /* Simple capture, from start to end, no wrapping */ obj->nextSampleIdx = 0; obj->endSampleIdx = 0; // DATALOG_SAMPLE_COUNT; obj->dataStartIdx = 0; obj->triggerIdx = 0; obj->trigger.state = DATALOG_TRIGGER_STATE_Running; obj->state = DATALOG_STATE_Running; #endif /* SUPPORT_PRETRIGGER_AND_WRAPPED_DATA */ } } if (obj->trigger.state == DATALOG_TRIGGER_STATE_Running) { if (obj->downsamplecounter >= obj->downsample) { obj->downsamplecounter = 0; /* This is the actual sampling */ { int channel; for (channel = 0; channel < DATALOG_NUM_CHANNELS; channel++) { DATALOG_CHANNEL_s* pChannel = &obj->channel[channel]; if (pChannel->bEnabled) { DATALOG_SAMPLE_TYPE sample = *((DATALOG_SAMPLE_TYPE*) pChannel->pSource); pChannel->lastSample = pChannel->currentSample; pChannel->currentSample = sample; pChannel->samples[nextSampleIdx] = sample; } } nextSampleIdx++; if (nextSampleIdx >= DATALOG_SAMPLE_COUNT) nextSampleIdx = 0; obj->nextSampleIdx = nextSampleIdx; } /* Detect end of sampling */ if (obj->nextSampleIdx == obj->endSampleIdx) { obj->trigger.state = DATALOG_TRIGGER_STATE_Holding; obj->state = DATALOG_STATE_Holding; } } else { obj->downsamplecounter++; } } } else if (obj->trigger.mode == DATALOG_TRIGGER_MODE_Rolling) { /* Basic continous rolling mode, for debugging use */ uint16_t nextSampleIdx = obj->nextSampleIdx; int channel; for (channel = 0; channel < DATALOG_NUM_CHANNELS; channel++) { DATALOG_CHANNEL_s* pChannel = &obj->channel[channel]; if (pChannel->bEnabled) { DATALOG_SAMPLE_TYPE sample = *((DATALOG_SAMPLE_TYPE*) pChannel->pSource); pChannel->lastSample = pChannel->currentSample; pChannel->currentSample = sample; pChannel->samples[nextSampleIdx] = sample; } } nextSampleIdx++; if (nextSampleIdx >= DATALOG_SAMPLE_COUNT) { nextSampleIdx = 0; } obj->nextSampleIdx = nextSampleIdx; } } /* end of DATALOG_run() function */ bool DATALOG_checkTrigger(DATALOG_Handle handle) { DATALOG_Obj* obj = handle; bool bTriggered = false; if (obj->trigger.justArmed) { /* Don't trigger directly after arming */ obj->trigger.justArmed = false; return (false); } if (obj->trigger.state == DATALOG_TRIGGER_STATE_Armed) { DATALOG_TRIGGER_s* pTrigger = &obj->trigger; DATALOG_SAMPLE_TYPE currentSample = obj->channel[pTrigger->channel].currentSample; DATALOG_SAMPLE_TYPE lastSample = obj->channel[pTrigger->channel].lastSample; DATALOG_TRIGGER_EDGE_DIRECTION_e edge = pTrigger->edge; DATALOG_SAMPLE_TYPE level = pTrigger->level; switch (edge) { case DATALOG_TRIGGER_EDGE_DIRECTION_Rising: if (lastSample < level && currentSample >= level) { bTriggered = true; } break; case DATALOG_TRIGGER_EDGE_DIRECTION_Falling: if (lastSample > level && currentSample <= level) { bTriggered = true; } break; case DATALOG_TRIGGER_EDGE_DIRECTION_Both: if ((lastSample < level && currentSample >= level) || (lastSample > level && currentSample <= level)) { bTriggered = true; } break; } } return (bTriggered); } /* end of DATALOG_checkTrigger() function */ void DATALOG_clearChannelData(DATALOG_Handle handle, int channel) { DATALOG_Obj* obj = handle; DATALOG_CHANNEL_s* pChannel = &obj->channel[channel]; int sample; for (sample = 0; sample < DATALOG_SAMPLE_COUNT; sample++) { pChannel->samples[sample] = 0; } } /* end of DATALOG_clearChannelData() function */ void DATALOG_setChannel(DATALOG_Handle handle, uint16_t channel, DATALOG_SAMPLE_TYPE* pSample) { DATALOG_Obj* obj = handle; DATALOG_CHANNEL_s* pChannel = &obj->channel[channel]; pChannel->bEnabled = true; pChannel->pSource = pSample; } /* end of DATALOG_setChannel() function */ void DATALOG_setCommand(DATALOG_Handle handle, const DATALOG_COMMAND_e command) { DATALOG_Obj* obj = handle; obj->command = command; return; } /* end of DATALOG_setCommand() function */ void DATALOG_getChannelBuffer(DATALOG_Handle handle, const int channel, DATALOG_SAMPLE_TYPE** ppBuffer, uint16_t* pSizeBytes) { /* Does not support wrapped buffers */ DATALOG_Obj* obj = handle; *ppBuffer = &obj->channel[channel].samples[0]; *pSizeBytes = obj->endSampleIdx << 1; /* Samples are 16-bit, so we send twice the number of bytes */ if (obj->dataStartIdx == 0 && obj->endSampleIdx == 0) { // ToDo: Figure out way to support a full buffer, 60 samples in all *pSizeBytes = DATALOG_SAMPLE_COUNT * 2; } return; } void DATALOG_setSampleWindow(DATALOG_Handle handle) { DATALOG_Obj* obj = handle; uint16_t preTrigger = obj->trigger.preTrigger; uint16_t postTrigger = DATALOG_SAMPLE_COUNT - preTrigger; uint16_t preTriggerSamples = preTrigger; uint16_t postTriggerSamples = postTrigger; uint16_t dataStartIdx; if (preTriggerSamples > obj->nextSampleIdx) { // wrapped dataStartIdx = (obj->nextSampleIdx + DATALOG_SAMPLE_COUNT - preTriggerSamples); } else { dataStartIdx = obj->nextSampleIdx - preTriggerSamples; } obj->dataStartIdx = dataStartIdx; uint16_t endSampleIdx = obj->nextSampleIdx + postTriggerSamples; // Wrap if (endSampleIdx >= DATALOG_SAMPLE_COUNT) { endSampleIdx -= DATALOG_SAMPLE_COUNT; } obj->endSampleIdx = endSampleIdx; } /* end of DATALOG_setSampleWindow() function */ /* end of datalog.c */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
11,508
C
27.7725
127
0.601842
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/sto_pll_speed_pos_fdbk.c
/** ****************************************************************************** * @file sto_pll_speed_pos_fdbk.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of 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 */ /* Includes ------------------------------------------------------------------*/ #include "sto_pll_speed_pos_fdbk.h" #include "mc_math.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** * @defgroup SpeednPosFdbk_STO_PLL State Observer PLL Speed & Position Feedback. * @brief State Observer with PLL Speed & Position Feedback component of MCSDK. * * This component uses a State Observer coupled with a software PLL to provide an estimation of * the speed and the position of the rotor of the motor. * * See the [Speed & position feedback sensorless chapter of the User Manual](speed_pos_sensorless_bemf_reconstruction.md) for more details on the sensorless algorithm. * @{ */ /* Private defines -----------------------------------------------------------*/ #define C6_COMP_CONST1 ((int32_t)1043038) #define C6_COMP_CONST2 ((int32_t)10430) /* Private function prototypes -----------------------------------------------*/ static void STO_Store_Rotor_Speed(STO_PLL_Handle_t *pHandle, int16_t hRotor_Speed); static int16_t STO_ExecutePLL(STO_PLL_Handle_t *pHandle, int16_t hBemf_alfa_est, int16_t hBemf_beta_est); static void STO_InitSpeedBuffer(STO_PLL_Handle_t *pHandle); /** * @brief Initializes the @p pHandle of STate Observer (STO) PLL component. * */ __weak void STO_PLL_Init(STO_PLL_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif int16_t htempk; int32_t wAux; pHandle->ConsistencyCounter = pHandle->StartUpConsistThreshold; pHandle->EnableDualCheck = true; wAux = ((int32_t)1); pHandle->F3POW2 = 0U; htempk = (int16_t)(C6_COMP_CONST1 / pHandle->hF2); while (htempk != 0) { htempk /= ((int16_t)2); wAux *= ((int32_t)2); pHandle->F3POW2++; } pHandle->hF3 = (int16_t)wAux; wAux = ((int32_t)(pHandle->hF2)) * pHandle->hF3; pHandle->hC6 = (int16_t)(wAux / C6_COMP_CONST2); STO_PLL_Clear(pHandle); PID_HandleInit(&pHandle->PIRegulator); /* Acceleration measurement set to zero */ pHandle->_Super.hMecAccelUnitP = 0; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif return; } /** * @brief Necessary empty return to implement fictitious IRQ_Handler. * * @param pHandle: Handler of the current instance of the STO component. * @param uint8_t: Fictitious interrupt flag. */ //cstat !MISRAC2012-Rule-8.13 !RED-func-no-effect __weak void STO_PLL_Return(STO_PLL_Handle_t *pHandle, uint8_t flag) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if ((MC_NULL == (void *)pHandle) || ((uint8_t)0 == flag)) { /* Nothing to do */ } else { /* Nothing to do */ } #endif return; } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief Calculates the estimated electrical angle. * * Executes Luenberger state observer equations and calls * PLL to compute a new speed estimation and * update the estimated electrical angle. * * @param pHandle: Handler of the current instance of the STO component. * @param pInput: Pointer to the observer inputs structure. * @retval int16_t Rotor electrical angle (s16Degrees). */ //cstat !MISRAC2012-Rule-8.13 __weak int16_t STO_PLL_CalcElAngle(STO_PLL_Handle_t *pHandle, Observer_Inputs_t *pInputs) { int16_t retValue; if ((MC_NULL == pHandle) || (MC_NULL == pInputs)) { retValue = 0; } else { int32_t wAux; int32_t wDirection; int32_t wIalfa_est_Next; int32_t wIbeta_est_Next; int32_t wBemf_alfa_est_Next; int32_t wBemf_beta_est_Next; int16_t hAux; int16_t hAux_Alfa; int16_t hAux_Beta; int16_t hIalfa_err; int16_t hIbeta_err; int16_t hRotor_Speed; int16_t hValfa; int16_t hVbeta; if (pHandle->wBemf_alfa_est > (((int32_t)pHandle->hF2) * INT16_MAX)) { pHandle->wBemf_alfa_est = INT16_MAX * ((int32_t)pHandle->hF2); } else if (pHandle->wBemf_alfa_est <= (-INT16_MAX * ((int32_t)pHandle->hF2))) { pHandle->wBemf_alfa_est = -INT16_MAX * ((int32_t)pHandle->hF2); } else { /* Nothing to do */ } #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 hAux_Alfa = (int16_t)(pHandle->wBemf_alfa_est >> pHandle->F2LOG); #else hAux_Alfa = (int16_t)(pHandle->wBemf_alfa_est / pHandle->hF2); #endif if (pHandle->wBemf_beta_est > (INT16_MAX * ((int32_t)pHandle->hF2))) { pHandle->wBemf_beta_est = INT16_MAX * ((int32_t)pHandle->hF2); } else if (pHandle->wBemf_beta_est <= (-INT16_MAX * ((int32_t)pHandle->hF2))) { pHandle->wBemf_beta_est = (-INT16_MAX * ((int32_t)pHandle->hF2)); } else { /* Nothing to do */ } #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 hAux_Beta = (int16_t)(pHandle->wBemf_beta_est >> pHandle->F2LOG); #else hAux_Beta = (int16_t)(pHandle->wBemf_beta_est / pHandle->hF2); #endif if (pHandle->Ialfa_est > (INT16_MAX * ((int32_t)pHandle->hF1))) { pHandle->Ialfa_est = INT16_MAX * ((int32_t)pHandle->hF1); } else if (pHandle->Ialfa_est <= (-INT16_MAX * ((int32_t)pHandle->hF1))) { pHandle->Ialfa_est = -INT16_MAX * ((int32_t)pHandle->hF1); } else { /* Nothing to do */ } if (pHandle->Ibeta_est > (INT16_MAX * ((int32_t)pHandle->hF1))) { pHandle->Ibeta_est = INT16_MAX * ((int32_t)pHandle->hF1); } else if (pHandle->Ibeta_est <= (-INT16_MAX * ((int32_t)pHandle->hF1))) { pHandle->Ibeta_est = -INT16_MAX * ((int32_t)pHandle->hF1); } else { /* Nothing to do */ } #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 hIalfa_err = (int16_t)(pHandle->Ialfa_est >> pHandle->F1LOG); #else hIalfa_err = (int16_t)(pHandle->Ialfa_est / pHandle->hF1); #endif hIalfa_err = hIalfa_err - pInputs->Ialfa_beta.alpha; #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 hIbeta_err = (int16_t)(pHandle->Ibeta_est >> pHandle->F1LOG); #else hIbeta_err = (int16_t)(pHandle->Ibeta_est / pHandle->hF1); #endif hIbeta_err = hIbeta_err - pInputs->Ialfa_beta.beta; wAux = ((int32_t)pInputs->Vbus) * pInputs->Valfa_beta.alpha; #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL hValfa = (int16_t)(wAux >> 16); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 #else hValfa = (int16_t)(wAux / 65536); #endif wAux = ((int32_t)pInputs->Vbus) * pInputs->Valfa_beta.beta; #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL hVbeta = ( int16_t ) ( wAux >> 16 ); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 #else hVbeta = (int16_t)(wAux / 65536); #endif /* alfa axes observer */ #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 hAux = (int16_t)(pHandle->Ialfa_est >> pHandle->F1LOG); #else hAux = (int16_t)(pHandle->Ialfa_est / pHandle->hF1); #endif wAux = ((int32_t)pHandle->hC1) * hAux; wIalfa_est_Next = pHandle->Ialfa_est - wAux; wAux = ((int32_t)pHandle->hC2) * hIalfa_err; wIalfa_est_Next += wAux; wAux = ((int32_t)pHandle->hC5) * hValfa; wIalfa_est_Next += wAux; wAux = ((int32_t)pHandle->hC3) * hAux_Alfa; wIalfa_est_Next -= wAux; wAux = ((int32_t)pHandle->hC4) * hIalfa_err; wBemf_alfa_est_Next = pHandle->wBemf_alfa_est + wAux; #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL wAux = (int32_t)hAux_Beta >> pHandle->F3POW2; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 #else wAux = ((int32_t)hAux_Beta) / pHandle->hF3; #endif wAux = wAux * pHandle->hC6; wAux = pHandle->_Super.hElSpeedDpp * wAux; wBemf_alfa_est_Next += wAux; /* beta axes observer */ #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 hAux = (int16_t)(pHandle->Ibeta_est >> pHandle->F1LOG); #else hAux = (int16_t)(pHandle->Ibeta_est / pHandle->hF1); #endif wAux = ((int32_t)pHandle->hC1) * hAux; wIbeta_est_Next = pHandle->Ibeta_est - wAux; wAux = ((int32_t)pHandle->hC2) * hIbeta_err; wIbeta_est_Next += wAux; wAux = ((int32_t)pHandle->hC5) * hVbeta; wIbeta_est_Next += wAux; wAux = ((int32_t)pHandle->hC3) * hAux_Beta; wIbeta_est_Next -= wAux; wAux = ((int32_t)pHandle->hC4) * hIbeta_err; wBemf_beta_est_Next = pHandle->wBemf_beta_est + wAux; #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL wAux = (int32_t)hAux_Alfa >> pHandle->F3POW2; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 #else wAux = ((int32_t)hAux_Alfa) / pHandle->hF3; #endif wAux = wAux * pHandle->hC6; wAux = pHandle->_Super.hElSpeedDpp * wAux; wBemf_beta_est_Next -= wAux; /* Calls the PLL blockset */ pHandle->hBemf_alfa_est = hAux_Alfa; pHandle->hBemf_beta_est = hAux_Beta; if (0 == pHandle->hForcedDirection) { /* We are in auxiliary mode, then rely on the speed detected */ if(pHandle->_Super.hElSpeedDpp >= 0) { wDirection = 1; } else { wDirection = -1; } } else { /* We are in main sensor mode, use a forced direction */ wDirection = pHandle->hForcedDirection; } hAux_Alfa = (int16_t)(hAux_Alfa * wDirection); hAux_Beta = (int16_t)(hAux_Beta * wDirection); hRotor_Speed = STO_ExecutePLL(pHandle, hAux_Alfa, -hAux_Beta); pHandle->_Super.InstantaneousElSpeedDpp = hRotor_Speed; STO_Store_Rotor_Speed(pHandle, hRotor_Speed); pHandle->_Super.hElAngle += hRotor_Speed; /* Storing previous values of currents and bemfs */ pHandle->Ialfa_est = wIalfa_est_Next; pHandle->wBemf_alfa_est = wBemf_alfa_est_Next; pHandle->Ibeta_est = wIbeta_est_Next; pHandle->wBemf_beta_est = wBemf_beta_est_Next; retValue = pHandle->_Super.hElAngle; } return (retValue); } /** * @brief Computes and returns the average mechanical speed. * * 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 #SPEED_UNIT. Average is computed considering a FIFO depth * equal to bSpeedBufferSizeUnit. Moreover it also computes and returns * the reliability state of the sensor. * * @param pHandle: Handler of the current instance of the STO component. * @param pMecSpeedUnit: Pointer to int16_t, used to return the rotor average * mechanical speed (expressed in #SPEED_UNIT). * @retval True if the sensor information is reliable, false otherwise. */ __weak bool STO_PLL_CalcAvrgMecSpeedUnit(STO_PLL_Handle_t *pHandle, int16_t *pMecSpeedUnit) { bool bAux; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if ((MC_NULL == pHandle) || (MC_NULL == pMecSpeedUnit)) { bAux = false; } else { #endif int32_t wAvrSpeed_dpp = (int32_t)0; int32_t wError; int32_t wAux; int32_t wAvrSquareSpeed; int32_t wAvrQuadraticError = 0; int32_t wObsBemf, wEstBemf; int32_t wObsBemfSq = 0; int32_t wEstBemfSq = 0; int32_t wEstBemfSqLo; bool bIs_Speed_Reliable = false; bool bIs_Bemf_Consistent = false; uint8_t i, bSpeedBufferSizeUnit = pHandle->SpeedBufferSizeUnit; for (i = 0U; i < bSpeedBufferSizeUnit; i++) { wAvrSpeed_dpp += (int32_t)(pHandle->Speed_Buffer[i]); } if (0U == bSpeedBufferSizeUnit) { /* Nothing to do */ } else { wAvrSpeed_dpp = wAvrSpeed_dpp / ((int16_t)bSpeedBufferSizeUnit); } for (i = 0U; i < bSpeedBufferSizeUnit; i++) { wError = ((int32_t)pHandle->Speed_Buffer[i]) - wAvrSpeed_dpp; wError = (wError * wError); wAvrQuadraticError += wError; } /* It computes the measurement variance */ wAvrQuadraticError = wAvrQuadraticError / ((int16_t)bSpeedBufferSizeUnit); /* The maximum variance acceptable is here calculated as a function of average speed */ wAvrSquareSpeed = wAvrSpeed_dpp * wAvrSpeed_dpp; int64_t lAvrSquareSpeed = (int64_t)(wAvrSquareSpeed) * (int64_t)pHandle->VariancePercentage; wAvrSquareSpeed = (int32_t)(lAvrSquareSpeed / (int64_t)128); if (wAvrQuadraticError < wAvrSquareSpeed) { bIs_Speed_Reliable = true; } /* Computation of Mechanical speed Unit */ wAux = wAvrSpeed_dpp * ((int32_t)pHandle->_Super.hMeasurementFrequency); wAux = wAux * ((int32_t)pHandle->_Super.SpeedUnit); wAux = wAux / ((int32_t)pHandle->_Super.DPPConvFactor); wAux = wAux / ((int16_t)pHandle->_Super.bElToMecRatio); *pMecSpeedUnit = (int16_t)wAux; pHandle->_Super.hAvrMecSpeedUnit = (int16_t)wAux; pHandle->IsSpeedReliable = bIs_Speed_Reliable; /* Bemf Consistency Check algorithm */ if (true == pHandle->EnableDualCheck) /* Do algorithm if it's enabled */ { /* wAux abs value */ //cstat !MISRAC2012-Rule-14.3_b !RED-func-no-effect !RED-cmp-never !RED-cond-never wAux = ((wAux < 0) ? (-wAux) : (wAux)); if (wAux < (int32_t)(pHandle->MaxAppPositiveMecSpeedUnit)) { /* Computation of Observed back-emf */ wObsBemf = (int32_t)pHandle->hBemf_alfa_est; wObsBemfSq = wObsBemf * wObsBemf; wObsBemf = (int32_t)pHandle->hBemf_beta_est; wObsBemfSq += wObsBemf * wObsBemf; /* Computation of Estimated back-emf */ wEstBemf = (wAux * 32767) / ((int16_t)pHandle->_Super.hMaxReliableMecSpeedUnit); wEstBemfSq = (wEstBemf * ((int32_t)pHandle->BemfConsistencyGain)) / 64; wEstBemfSq *= wEstBemf; /* Computation of threshold */ wEstBemfSqLo = wEstBemfSq - ((wEstBemfSq / 64) * ((int32_t)pHandle->BemfConsistencyCheck)); /* Check */ if (wObsBemfSq > wEstBemfSqLo) { bIs_Bemf_Consistent = true; } else { /* Nothing to do */ } } pHandle->IsBemfConsistent = bIs_Bemf_Consistent; pHandle->Obs_Bemf_Level = wObsBemfSq; pHandle->Est_Bemf_Level = wEstBemfSq; } else { bIs_Bemf_Consistent = true; } /* Decision making */ if (false == pHandle->IsAlgorithmConverged) { bAux = SPD_IsMecSpeedReliable (&pHandle->_Super, pMecSpeedUnit); } else { if ((false == pHandle->IsSpeedReliable) || (false == bIs_Bemf_Consistent)) { pHandle->ReliabilityCounter++; if (pHandle->ReliabilityCounter >= pHandle->Reliability_hysteresys) { pHandle->ReliabilityCounter = 0U; pHandle->_Super.bSpeedErrorNumber = pHandle->_Super.bMaximumSpeedErrorsNumber; bAux = false; } else { bAux = SPD_IsMecSpeedReliable (&pHandle->_Super, pMecSpeedUnit); } } else { pHandle->ReliabilityCounter = 0U; bAux = SPD_IsMecSpeedReliable (&pHandle->_Super, pMecSpeedUnit); } } #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif return (bAux); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Computes and updates the average electrical speed. * * This method 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 STO component. */ __weak void STO_PLL_CalcAvrgElSpeedDpp(STO_PLL_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif int32_t wSum = pHandle->DppBufferSum; int32_t wAvrSpeed_dpp; int16_t hSpeedBufferSizedpp = (int16_t)pHandle->SpeedBufferSizeDpp; int16_t hSpeedBufferSizeUnit = (int16_t)pHandle->SpeedBufferSizeUnit; int16_t hBufferSizeDiff; int16_t hIndexNew = (int16_t)pHandle->Speed_Buffer_Index; int16_t hIndexOld; int16_t hIndexOldTemp; hBufferSizeDiff = hSpeedBufferSizeUnit - hSpeedBufferSizedpp; if (0 == hBufferSizeDiff) { wSum = wSum + pHandle->Speed_Buffer[hIndexNew] - pHandle->SpeedBufferOldestEl; } else { hIndexOldTemp = hIndexNew + hBufferSizeDiff; if (hIndexOldTemp >= hSpeedBufferSizeUnit) { hIndexOld = hIndexOldTemp - hSpeedBufferSizeUnit; } else { hIndexOld = hIndexOldTemp; } wSum = wSum + pHandle->Speed_Buffer[hIndexNew] - pHandle->Speed_Buffer[hIndexOld]; } #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 wAvrSpeed_dpp = wSum >> pHandle->SpeedBufferSizeDppLOG; #else if ((int16_t )0 == hSpeedBufferSizedpp) { /* Nothing to do */ wAvrSpeed_dpp = wSum; } else { wAvrSpeed_dpp = wSum / hSpeedBufferSizedpp; } #endif pHandle->_Super.hElSpeedDpp = (int16_t)wAvrSpeed_dpp; pHandle->DppBufferSum = wSum; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Clears state observer component by re-initializing private variables in @p pHandle. * */ __weak void STO_PLL_Clear(STO_PLL_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->Ialfa_est = (int32_t)0; pHandle->Ibeta_est = (int32_t)0; pHandle->wBemf_alfa_est = (int32_t)0; pHandle->wBemf_beta_est = (int32_t)0; pHandle->_Super.hElAngle = (int16_t)0; pHandle->_Super.hElSpeedDpp = (int16_t)0; pHandle->ConsistencyCounter = 0u; pHandle->ReliabilityCounter = 0u; pHandle->IsAlgorithmConverged = false; pHandle->IsBemfConsistent = false; pHandle->Obs_Bemf_Level = (int32_t)0; pHandle->Est_Bemf_Level = (int32_t)0; pHandle->DppBufferSum = (int32_t)0; pHandle->ForceConvergency = false; pHandle->ForceConvergency2 = false; STO_InitSpeedBuffer(pHandle); PID_SetIntegralTerm(& pHandle->PIRegulator, (int32_t)0); #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Stores in @p pHandle the latest calculated value of @p hRotor_Speed. * */ inline static void STO_Store_Rotor_Speed(STO_PLL_Handle_t *pHandle, int16_t hRotor_Speed) { uint8_t bBuffer_index = pHandle->Speed_Buffer_Index; bBuffer_index++; if (bBuffer_index == pHandle->SpeedBufferSizeUnit) { bBuffer_index = 0U; } else { /* Nothing to do */ } pHandle->SpeedBufferOldestEl = pHandle->Speed_Buffer[bBuffer_index]; pHandle->Speed_Buffer[bBuffer_index] = hRotor_Speed; pHandle->Speed_Buffer_Index = bBuffer_index; } /** * @brief Executes PLL algorithm for rotor position extraction from B-emf alpha and beta. * * @param pHandle: Handler of the current instance of the STO component. * @param hBemf_alfa_est: Estimated Bemf alpha on the stator reference frame. * @param hBemf_beta_est: Estimated Bemf beta on the stator reference frame. * @retval */ inline static int16_t STO_ExecutePLL(STO_PLL_Handle_t *pHandle, int16_t hBemf_alfa_est, int16_t hBemf_beta_est) { int32_t wAlfa_Sin_tmp; int32_t wBeta_Cos_tmp; int16_t hAux1; int16_t hAux2; int16_t hOutput; Trig_Components Local_Components; Local_Components = MCM_Trig_Functions(pHandle->_Super.hElAngle); /* Alfa & Beta BEMF multiplied by Cos & Sin */ wAlfa_Sin_tmp = ((int32_t )hBemf_alfa_est) * ((int32_t )Local_Components.hSin); wBeta_Cos_tmp = ((int32_t )hBemf_beta_est) * ((int32_t )Local_Components.hCos); #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL hAux1 = (int16_t)(wBeta_Cos_tmp >> 15); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 #else hAux1 = (int16_t)(wBeta_Cos_tmp / 32768); #endif #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL hAux2 = (int16_t)(wAlfa_Sin_tmp >> 15); //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 #else hAux2 = (int16_t)(wAlfa_Sin_tmp / 32768); #endif /* Speed PI regulator */ hOutput = PI_Controller(& pHandle->PIRegulator, (int32_t)(hAux1 ) - hAux2); return (hOutput); } /** * @brief Clears the estimated speed buffer in @p pHandle. * */ static void STO_InitSpeedBuffer(STO_PLL_Handle_t * pHandle) { uint8_t b_i; uint8_t bSpeedBufferSize = pHandle->SpeedBufferSizeUnit; /* Init speed buffer */ for (b_i = 0U; b_i < bSpeedBufferSize; b_i++) { pHandle->Speed_Buffer[b_i] = (int16_t)0; } pHandle->Speed_Buffer_Index = 0U; pHandle->SpeedBufferOldestEl = (int16_t)0; } /** * @brief Checks if the state observer algorithm converged. * * Internally performs a set of checks necessary to state whether * the state observer 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 STO component. * @param hForcedMecSpeedUnit: Mechanical speed in 0.1Hz unit as forced by VSS. * @retval bool True if the estimated angle and speed are reliables, false otherwise. */ __weak bool STO_PLL_IsObserverConverged(STO_PLL_Handle_t *pHandle, int16_t *phForcedMecSpeedUnit) { bool bAux = false; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if ((MC_NULL == pHandle) || (MC_NULL == phForcedMecSpeedUnit)) { /* Nothing to do */ } else { #endif int32_t wAux; int32_t wtemp; int16_t hEstimatedSpeedUnit; int16_t hUpperThreshold; int16_t hLowerThreshold; if (true == pHandle->ForceConvergency2) { *phForcedMecSpeedUnit = pHandle->_Super.hAvrMecSpeedUnit; } else { /* Nothing to do */ } if (true == pHandle->ForceConvergency) { bAux = true; pHandle->IsAlgorithmConverged = true; pHandle->_Super.bSpeedErrorNumber = 0U; } else { hEstimatedSpeedUnit = pHandle->_Super.hAvrMecSpeedUnit; wtemp = ((int32_t)hEstimatedSpeedUnit) * ((int32_t)*phForcedMecSpeedUnit); if (wtemp > 0) { if (hEstimatedSpeedUnit < 0) { hEstimatedSpeedUnit = -hEstimatedSpeedUnit; } if (*phForcedMecSpeedUnit < 0) { *phForcedMecSpeedUnit = -*phForcedMecSpeedUnit; } wAux = ((int32_t)*phForcedMecSpeedUnit) * ((int16_t)pHandle->SpeedValidationBand_H); hUpperThreshold = (int16_t)(wAux / ((int32_t)16)); wAux = ((int32_t)*phForcedMecSpeedUnit) * ((int16_t)pHandle->SpeedValidationBand_L); hLowerThreshold = (int16_t)(wAux / ((int32_t)16)); /* If the variance of the estimated speed is low enough... */ if (true == pHandle->IsSpeedReliable) { if ((uint16_t)hEstimatedSpeedUnit > pHandle->MinStartUpValidSpeed) { /* ...and the estimated value is quite close to the expected value... */ if (hEstimatedSpeedUnit >= hLowerThreshold) { if (hEstimatedSpeedUnit <= hUpperThreshold) { pHandle->ConsistencyCounter++; /* ...for hConsistencyThreshold consecutive times... */ if (pHandle->ConsistencyCounter >= pHandle->StartUpConsistThreshold) { /* The algorithm converged */ bAux = true; pHandle->IsAlgorithmConverged = true; pHandle->_Super.bSpeedErrorNumber = 0U; } } else { pHandle->ConsistencyCounter = 0U; } } else { pHandle->ConsistencyCounter = 0U; } } else { pHandle->ConsistencyCounter = 0U; } } else { pHandle->ConsistencyCounter = 0U; } } else { /* Nothing to do */ } } #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif return (bAux); } /** * @brief Exports estimated Bemf alpha-beta from @p pHandle. * * @retval alphabeta_t Bemf alpha-beta. */ //cstat !MISRAC2012-Rule-8.13 __weak alphabeta_t STO_PLL_GetEstimatedBemf(STO_PLL_Handle_t *pHandle) { alphabeta_t vaux; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { vaux.alpha = 0; vaux.beta = 0; } else { #endif vaux.alpha = pHandle->hBemf_alfa_est; vaux.beta = pHandle->hBemf_beta_est; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif return (vaux); } /** * @brief Exports from @p pHandle the stator current alpha-beta as estimated by state observer. * * @retval alphabeta_t State observer estimated stator current Ialpha-beta. */ //cstat !MISRAC2012-Rule-8.13 __weak alphabeta_t STO_PLL_GetEstimatedCurrent(STO_PLL_Handle_t *pHandle) { alphabeta_t iaux; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { iaux.alpha = 0; iaux.beta = 0; } else { #endif #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 iaux.alpha = (int16_t)(pHandle->Ialfa_est >> pHandle->F1LOG); #else iaux.alpha = (int16_t)(pHandle->Ialfa_est / pHandle->hF1); #endif #ifndef FULL_MISRA_C_COMPLIANCY_STO_PLL //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 iaux.beta = (int16_t)(pHandle->Ibeta_est >> pHandle->F1LOG); #else iaux.beta = (int16_t)(pHandle->Ibeta_est / pHandle->hF1); #endif #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif return (iaux); } /** * @brief Exports current observer gains from @p pHandle and to parameters @p phC2 and @p phC4. * */ //cstat !MISRAC2012-Rule-8.13 __weak void STO_PLL_GetObserverGains(STO_PLL_Handle_t *pHandle, int16_t *phC2, int16_t *phC4) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if ((MC_NULL == pHandle) || (MC_NULL == phC2) || (MC_NULL == phC4)) { /* Nothing to do */ } else { #endif *phC2 = pHandle->hC2; *phC4 = pHandle->hC4; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Stores in @p pHandle the new values @p hhC1 and @p hhC2 for observer gains. * */ //cstat !MISRAC2012-Rule-8.13 __weak void STO_PLL_SetObserverGains(STO_PLL_Handle_t *pHandle, int16_t hhC1, int16_t hhC2) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->hC2 = hhC1; pHandle->hC4 = hhC2; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Exports current PLL gains from @p pHandle to @p pPgain and @p pIgain. * */ //cstat !MISRAC2012-Rule-8.13 __weak void STO_GetPLLGains(STO_PLL_Handle_t *pHandle, int16_t *pPgain, int16_t *pIgain) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if ((MC_NULL == pHandle) || (MC_NULL == pPgain) || (MC_NULL == pIgain)) { /* Nothing to do */ } else { #endif *pPgain = PID_GetKP(& pHandle->PIRegulator); *pIgain = PID_GetKI(& pHandle->PIRegulator); #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Stores in @p pHandle the new values @p hPgain and @p hIgain for PLL gains. * */ __weak void STO_SetPLLGains(STO_PLL_Handle_t *pHandle, int16_t hPgain, int16_t hIgain) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif PID_SetKP(&pHandle->PIRegulator, hPgain); PID_SetKI(&pHandle->PIRegulator, hIgain); #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Empty function. Could be declared to set instantaneous information on rotor mechanical angle. * * Note: Mechanical angle management is not implemented in this * version of State observer sensor class. * * @param pHandle: Handler of the current instance of the STO component. * @param hMecAngle: Instantaneous measure of rotor mechanical angle. */ //cstat !MISRAC2012-Rule-8.13 !RED-func-no-effect __weak void STO_PLL_SetMecAngle(STO_PLL_Handle_t *pHandle, int16_t hMecAngle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if ((MC_NULL == (void *)pHandle) || ((int16_t)0 == hMecAngle)) { /* Nothing to do */ } else { /* nothing to do */ } #endif } /** * @brief Resets the PLL integral term during on-the-fly startup. * * @param pHandle: Handler of the current instance of the STO component. */ __weak void STO_OTF_ResetPLL(STO_Handle_t * pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif STO_PLL_Handle_t *pHdl = (STO_PLL_Handle_t *)pHandle->_Super; //cstat !MISRAC2012-Rule-11.3 PID_SetIntegralTerm(&pHdl->PIRegulator, (int32_t)0); #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__( ( section ( ".ccmram" ) ) ) #endif #endif /** * @brief Resets the PLL integral term. * * @param pHandle: Handler of the current instance of the STO component. */ __weak void STO_ResetPLL(STO_PLL_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif PID_SetIntegralTerm(&pHandle->PIRegulator, (int32_t)0); #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Sends locking info for PLL. * * @param pHandle: Handler of the current instance of the STO component. * @param hElSpeedDpp: Estimated average electrical speed expressed in dpp. * @param hElAngle: Estimated electrical angle expressed in s16Degrees. */ __weak void STO_SetPLL(STO_PLL_Handle_t *pHandle, int16_t hElSpeedDpp, int16_t hElAngle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif PID_SetIntegralTerm(&pHandle->PIRegulator, ((int32_t)hElSpeedDpp) * (int32_t)(PID_GetKIDivisor(&pHandle->PIRegulator))); pHandle->_Super.hElAngle = hElAngle; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Exports estimated Bemf squared level stored in @p pHandle. * * @retval int32_t Magnitude of estimated Bemf Level squared based on speed measurement. */ //cstat !MISRAC2012-Rule-8.13 __weak int32_t STO_PLL_GetEstimatedBemfLevel(STO_PLL_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB return ((MC_NULL == pHandle) ? 0 : pHandle->Est_Bemf_Level); #else return (pHandle->Est_Bemf_Level); #endif } /** * @brief Exports observed Bemf squared level stored in @p pHandle. * * @retval int32_t Magnitude of observed Bemf level squared. */ //cstat !MISRAC2012-Rule-8.13 __weak int32_t STO_PLL_GetObservedBemfLevel(STO_PLL_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB return ((MC_NULL == pHandle) ? 0 : pHandle->Obs_Bemf_Level); #else return (pHandle->Obs_Bemf_Level); #endif } /** * @brief Enables/Disables additional reliability check based on observed Bemf. * * @param pHandle: Handler of the current instance of the STO component. * @param bSel Enable/Disable check. */ __weak void STO_PLL_BemfConsistencyCheckSwitch(STO_PLL_Handle_t *pHandle, bool bSel) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->EnableDualCheck = bSel; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Checks if the Bemf is consistent. * * @param pHandle: Handler of the current instance of the STO component. * @retval bool True when observed Bemfs are consistent with expectation, false otherwise. */ //cstat !MISRAC2012-Rule-8.13 __weak bool STO_PLL_IsBemfConsistent(STO_PLL_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB return ((MC_NULL == pHandle) ? false : pHandle->IsBemfConsistent); #else return (pHandle->IsBemfConsistent); #endif } /** * @brief Checks the value of the variance. * * @param pHandle: Handler of the current instance of the STO component. * @retval bool True if the speed measurement variance is lower than threshold VariancePercentage, false otherwise. */ __weak bool STO_PLL_IsVarianceTight(const STO_Handle_t *pHandle) { bool tempStatus; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { tempStatus = false; } else { #endif const STO_PLL_Handle_t *pHdl = (STO_PLL_Handle_t *)pHandle->_Super; //cstat !MISRAC2012-Rule-11.3 tempStatus = pHdl->IsSpeedReliable; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif return (tempStatus); } /** * @brief Forces the state-observer to declare convergency. * * @param pHandle: Handler of the current instance of the STO component. */ __weak void STO_PLL_ForceConvergency1(STO_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif STO_PLL_Handle_t *pHdl = (STO_PLL_Handle_t *)pHandle->_Super; //cstat !MISRAC2012-Rule-11.3 pHdl->ForceConvergency = true; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Forces the state-observer to declare convergency. * * @param pHandle: Handler of the current instance of the STO component. */ __weak void STO_PLL_ForceConvergency2(STO_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif STO_PLL_Handle_t *pHdl = (STO_PLL_Handle_t *)pHandle->_Super; //cstat !MISRAC2012-Rule-11.3 pHdl->ForceConvergency2 = true; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Sets the Absolute value of minimum mechanical speed (expressed in * the unit defined by #SPEED_UNIT) required to validate the start-up. * * @param pHandle: Handler of the current instance of the STO component. * @param hMinStartUpValidSpeed: Absolute value of minimum mechanical speed. */ __weak void STO_SetMinStartUpValidSpeedUnit(STO_PLL_Handle_t *pHandle, uint16_t hMinStartUpValidSpeed) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->MinStartUpValidSpeed = hMinStartUpValidSpeed; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @brief Sets the rotation @p direction in @p pHandle. */ __weak void STO_SetDirection(STO_PLL_Handle_t *pHandle, int8_t direction) { #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->hForcedDirection = direction; #ifdef NULL_PTR_CHECK_STO_PLL_SPD_POS_FDB } #endif } /** * @} */ /** * @} */ /** @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
36,481
C
27.019969
168
0.635481
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/ntc_temperature_sensor.c
/** ****************************************************************************** * @file ntc_temperature_sensor.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the Temperature Sensor 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 TemperatureSensor */ /* Includes ------------------------------------------------------------------*/ #include "ntc_temperature_sensor.h" /** @addtogroup MCSDK * @{ */ /** @defgroup TemperatureSensor NTC Temperature Sensor * @brief Allows to read the temperature of the heat sink * * This component implements both a virtual and a real temperature sensor, * depending on the sensor availability. * * Access to the MCU peripherals needed to acquire the temperature (GPIO and ADC * used for regular conversion) is managed by the PWM component used in the Motor * Control subsystem. As a consequence, this NTC temperature sensor implementation * is hardware-independent. * * If a real temperature sensor is available (Sensor Type = #REAL_SENSOR), * this component can handle NTC sensors or, more generally, analog temperature sensors * which output is related to the temperature by the following formula: * * @f[ * V_{out} = V_0 + \frac{dV}{dT} \cdot ( T - T_0) * @f] * * In case of Pull up configuration @f$\frac{dV}{dT}@f$ is positive and @f$V_0@f$ is low. * In case of Pull down configuration @f$\frac{dV}{dT}@f$ is negative and @f$V_0@f$ is high. * * In case a real temperature sensor is not available (Sensor Type = #VIRTUAL_SENSOR), * This component will always returns a constant, programmable, temperature. * * @{ */ /* Private function prototypes -----------------------------------------------*/ uint16_t NTC_SetFaultState(NTC_Handle_t *pHandle); /* Private functions ---------------------------------------------------------*/ /** * @brief Returns fault when temperature exceeds the related temperature voltage protection threshold * * @param pHandle : Pointer on Handle structure of TemperatureSensor component * * @retval Fault status : Updated internal fault status */ __weak uint16_t NTC_SetFaultState(NTC_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13 { uint16_t hFault; #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS if (MC_NULL == pHandle) { hFault = MC_SW_ERROR; } else { #endif if (pHandle->hAvTemp_d > pHandle->hOverTempThreshold) { hFault = MC_OVER_TEMP; } else if (pHandle->hAvTemp_d < pHandle->hOverTempDeactThreshold) { hFault = MC_NO_ERROR; } else { hFault = pHandle->hFaultState; } #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS } #endif return (hFault); } /* Functions ---------------------------------------------------- */ /** * @brief Initializes temperature sensing conversions * * @param pHandle : Pointer on Handle structure of TemperatureSensor component * */ __weak void NTC_Init(NTC_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif if (REAL_SENSOR == pHandle->bSensorType) { NTC_Clear(pHandle); } else /* case VIRTUAL_SENSOR */ { pHandle->hFaultState = MC_NO_ERROR; pHandle->hAvTemp_d = pHandle->hExpectedTemp_d; } #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS } #endif } /** * @brief Initializes internal average temperature computed value * * @param pHandle : Pointer on Handle structure of TemperatureSensor component */ __weak void NTC_Clear(NTC_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS if (MC_NULL == pHandle) { /* nothing to do */ } else { #endif pHandle->hAvTemp_d = 0U; #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS } #endif } /** * @brief Performs the temperature sensing average computation after an ADC conversion * * @param pHandle : Pointer on Handle structure of TemperatureSensor component * * @retval Fault status : Error reported in case of an over temperature detection */ __weak uint16_t NTC_CalcAvTemp(NTC_Handle_t *pHandle, uint16_t rawValue) { uint16_t returnValue; #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS if (MC_NULL == pHandle) { returnValue = 0U; } else { #endif if (REAL_SENSOR == pHandle->bSensorType) { uint16_t hAux; hAux = rawValue; if (0xFFFFU == hAux) { /* Nothing to do */ } else { uint32_t wtemp; wtemp = (uint32_t)(pHandle->hLowPassFilterBW) - 1U; wtemp *= ((uint32_t)pHandle->hAvTemp_d); wtemp += hAux; wtemp /= ((uint32_t)pHandle->hLowPassFilterBW); pHandle->hAvTemp_d = (uint16_t)wtemp; } pHandle->hFaultState = NTC_SetFaultState(pHandle); } else /* case VIRTUAL_SENSOR */ { pHandle->hFaultState = MC_NO_ERROR; } returnValue = pHandle->hFaultState; #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS } #endif return (returnValue); } /** * @brief Returns latest averaged temperature measured expressed in u16Celsius * * @param pHandle : Pointer on Handle structure of TemperatureSensor component * * @retval AverageTemperature : Current averaged temperature measured (in u16Celsius) */ __weak uint16_t NTC_GetAvTemp_d(const NTC_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13 { #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS return ((MC_NULL == pHandle) ? 0U : pHandle->hAvTemp_d); #else return (pHandle->hAvTemp_d); #endif } /** * @brief Returns latest averaged temperature expressed in Celsius degrees * * @param pHandle : Pointer on Handle structure of TemperatureSensor component * * @retval AverageTemperature : Latest averaged temperature measured (in Celsius degrees) */ __weak int16_t NTC_GetAvTemp_C(NTC_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13 { int16_t returnValue; #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS if (MC_NULL == pHandle) { returnValue = 0; } else { #endif int32_t wTemp; if (REAL_SENSOR == pHandle->bSensorType) { wTemp = (int32_t)pHandle->hAvTemp_d; wTemp -= ((int32_t)pHandle->wV0); wTemp *= pHandle->hSensitivity; #ifndef FULL_MISRA_C_COMPLIANCY_NTC_TEMP //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 wTemp = (wTemp >> 16) + (int32_t)pHandle->hT0; #else wTemp = (wTemp / 65536) + (int32_t)pHandle->hT0; #endif } else { wTemp = (int32_t)pHandle->hExpectedTemp_C; } returnValue = (int16_t)wTemp; #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS } #endif return (returnValue); } /** * @brief Returns Temperature measurement fault status * * Fault status can be either #MC_OVER_TEMP when measure exceeds the protection threshold values or * #MC_NO_ERROR if it is inside authorized range. * * @param pHandle: Pointer on Handle structure of TemperatureSensor component. * * @retval Fault status : read internal fault state */ __weak uint16_t NTC_CheckTemp(const NTC_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_NTC_TEMP_SENS return ((MC_NULL == pHandle) ? 0U : pHandle->hFaultState); #else return (pHandle->hFaultState); #endif } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,870
C
26.141379
102
0.62033
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/fixpmath.c
/** ****************************************************************************** * @file fixpmath.c * @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 * ****************************************************************************** */ /* fixpmath.c */ #include "fixpmath.h" #include <math.h> /* fabsf() */ #include "mathlib.h" #include "mc_stm_types.h" /* Required for CORDIC */ #if defined(CORDIC) #define FIXPMATH_USE_CORDIC #endif #ifdef FIXPMATH_USE_CORDIC // Number of cycles can be tuned as a compromise between calculation time and precision #define CORDIC_CONFIG_BASE_COSSIN (LL_CORDIC_PRECISION_6CYCLES | LL_CORDIC_SCALE_0 | LL_CORDIC_NBWRITE_2 |\ LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS) /* CORDIC FUNCTION: COSINE only q1.31 */ #define CORDIC_CONFIG_COSINE (CORDIC_CONFIG_BASE_COSSIN | LL_CORDIC_FUNCTION_COSINE) /* CORDIC FUNCTION: SINE only q1.31 */ #define CORDIC_CONFIG_SINE (CORDIC_CONFIG_BASE_COSSIN | LL_CORDIC_FUNCTION_SINE) /* CORDIC FUNCTION: COSINE and SINE q1.31 */ #define CORDIC_CONFIG_COSINE_AND_SINE (CORDIC_CONFIG_BASE_COSSIN | LL_CORDIC_FUNCTION_COSINE | LL_CORDIC_NBREAD_2) /* CORDIC FUNCTION: PHASE q1.31 (Angle and magnitude computation) */ #define CORDIC_CONFIG_PHASE (LL_CORDIC_FUNCTION_PHASE | LL_CORDIC_PRECISION_15CYCLES | LL_CORDIC_SCALE_0 |\ LL_CORDIC_NBWRITE_2 | LL_CORDIC_NBREAD_2 |\ LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS) /* CORDIC FUNCTION: SQUAREROOT q1.31 */ #define CORDIC_CONFIG_SQRT (LL_CORDIC_FUNCTION_SQUAREROOT | LL_CORDIC_PRECISION_3CYCLES | LL_CORDIC_SCALE_1 |\ LL_CORDIC_NBWRITE_1 | LL_CORDIC_NBREAD_1 |\ LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS) // ToDo: Use LL_CORDIC_FUNCTION_HCOSINE to calculate EXP #define ANGLE_CORDIC_TO_PU(angle_cordic) (angle_cordic >> 2) & (FIXP30(1.0f)-1) /* scale and wrap cordic angle to per unit */ #define ANGLE_PU_TO_CORDIC(angle_pu) (angle_pu << 2) #define ANGLE_FP24_PU_TO_CORDIC(angle_pu) (angle_pu << 8) #endif /* FIXPMATH_USE_CORDIC */ /* fixptable is a table of pre-calculated powers of 2 as float value */ const float FIXPSCALED_fixptable[] = { (float) (1UL << 0), /* 1.0f, which is the maximum value which will fit in an fixp30_t */ (float) (1UL << 1), (float) (1UL << 2), (float) (1UL << 3), (float) (1UL << 4), (float) (1UL << 5), (float) (1UL << 6), (float) (1UL << 7), /* i = 7, fixptable[i] == 128.0f, fixpFmt = 31 - 7 = 24 */ (float) (1UL << 8), (float) (1UL << 9), (float) (1UL << 10), (float) (1UL << 11), (float) (1UL << 12), (float) (1UL << 13), (float) (1UL << 14), (float) (1UL << 15), (float) (1UL << 16), (float) (1UL << 17), (float) (1UL << 18), (float) (1UL << 19), (float) (1UL << 20), (float) (1UL << 21), (float) (1UL << 22), (float) (1UL << 23), (float) (1UL << 24), (float) (1UL << 25), (float) (1UL << 26), (float) (1UL << 27), (float) (1UL << 28), (float) (1UL << 29), (float) (1UL << 30), /* 1073741824.0f, which is the maximum value which will fit in an fixp1_t */ (float) (1UL << 31), /* 2147483648.0f, which is the maximum value which will fit in an fixp0_t */ (float) (1ULL << 32), (float) (1ULL << 33), (float) (1ULL << 34), (float) (1ULL << 35), (float) (1ULL << 36), (float) (1ULL << 37), (float) (1ULL << 38), (float) (1ULL << 39), (float) (1ULL << 40), (float) (1ULL << 41), (float) (1ULL << 42), (float) (1ULL << 43), }; void FIXPMATH_init(void) { MATHLIB_init(); } void FIXPSCALED_floatToFIXPscaled(const float value, FIXP_scaled_t *pFps) { int i; fixpFmt_t fixpFmt = 0; /* use fixp0_t if number will not fit at all */ /* the absolute value is used for comparisons, but the actual value for the final calculation */ float absvalue = fabsf(value); /* Figure out which scale will fit the float provided */ for (i = 0; i <= 31; i++) { if (FIXPSCALED_fixptable[i] > absvalue) /* check if it will fit */ { /* the qFmt for the result */ fixpFmt = 31 - i; break; } /* We either find a fit, or use _iq0 by default */ } pFps->fixpFmt = fixpFmt; pFps->value = (long) (value * FIXPSCALED_fixptable[fixpFmt]); /* may be negative */ } /* end of FIXPSCALED_floatToFIXPscaled() function */ void FIXPSCALED_floatToFIXPscaled_exp(const float value, FIXP_scaled_t *pFps, fixpFmt_t exponent) { pFps->fixpFmt = exponent; pFps->value = (long) (value * FIXPSCALED_fixptable[exponent]); /* may be negative */ } /* end of FIXPSCALED_floatToFIXPscaled_exp() function */ float_t FIXPSCALED_FIXPscaledToFloat(const FIXP_scaled_t *pFps) { return (float) ((float) pFps->value / FIXPSCALED_fixptable[pFps->fixpFmt]); } /* end of FIXPSCALED_FIXPscaledToFloat() function */ void FIXPSCALED_doubleToFIXPscaled(const double value, FIXP_scaled_t *pFps) { int i; fixpFmt_t fixpFmt = 0; /* use fixp0_t if number will not fit at all */ /* the absolute value is used for comparisons, but the actual value for the final calculation */ double absvalue = fabs(value); /* Figure out which scale will fit the float provided */ for (i = 0; i <= 31; i++) { if ((double)FIXPSCALED_fixptable[i] > absvalue) /* check if it will fit */ { /* the qFmt for the result */ fixpFmt = 31 - i; break; } /* We either find a fit, or use fixp0_t by default */ } pFps->fixpFmt = fixpFmt; pFps->value = (long) (value * (double)FIXPSCALED_fixptable[fixpFmt]); /* may be negative */ } /* end of FIXPSCALED_floatToFIXPscaled() function */ 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) { /* fixed point scaling factor */ /* Calculated using bitshifts, to avoid using the pow function */ float fixpFmt_factor; int_least8_t lshift = target_fixpFmt - source_fixpFmt; if (lshift >= 0) { /* Positive shift, giving 2^n */ fixpFmt_factor = (float) (1ul << lshift); } else { /* Negative shift, where we need to divide to calculate the corresponding factor 1/2^abs(n) */ fixpFmt_factor = (float) (1.0f / (1ul << (-lshift))); } /* full scale scaling factor */ float fullscale_factor = source_fullscale / target_fullscale; /* data scaling factor */ /* as given */ /* total scaling factor is the product of these three factors */ float ds = fixpFmt_factor * fullscale_factor * datascale_factor; /* Convert float to fixed point in optimal scale */ FIXPSCALED_floatToFIXPscaled(ds, pFps); } /* end of FIXPSCALED_calculateScaleFactor() function */ #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif void FIXP30_CosSinPU(fixp30_t angle_pu, FIXP_CosSin_t *pCosSin) { #if defined(FIXPMATH_USE_CORDIC) __disable_irq(); WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_COSINE_AND_SINE); LL_CORDIC_WriteData(CORDIC, ANGLE_PU_TO_CORDIC(angle_pu)); LL_CORDIC_WriteData(CORDIC, FIXP30(1.0f)); while (HAL_IS_BIT_CLR(CORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ pCosSin->cos = LL_CORDIC_ReadData(CORDIC); pCosSin->sin = LL_CORDIC_ReadData(CORDIC); __enable_irq(); #else /* FIXPMATH_USE_CORDIC */ angle_pu = (angle_pu & 0x3FFFFFFFul) >> (30-15) ; /* Wrap the angle by ANDing */ Vector_cossin_s cossin = MATHLIB_cossin(angle_pu); pCosSin->cos = cossin.cos << (30-15); pCosSin->sin = cossin.sin << (30-15); #endif /* FIXPMATH_USE_CORDIC */ } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif void FIXP30_polar(const fixp30_t x, const fixp30_t y, fixp30_t *pAngle_pu, fixp30_t *pMagnitude) { #ifdef FIXPMATH_USE_CORDIC __disable_irq(); WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_PHASE); LL_CORDIC_WriteData(CORDIC, x); LL_CORDIC_WriteData(CORDIC, y); while (HAL_IS_BIT_CLR(CORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ *pAngle_pu = ANGLE_CORDIC_TO_PU(LL_CORDIC_ReadData(CORDIC)); *pMagnitude = LL_CORDIC_ReadData(CORDIC); __enable_irq(); #else MATHLIB_polar(x, y, pAngle_pu, pMagnitude); #endif } fixp_t FIXP_mag(const fixp_t a, const fixp_t b) { fixp_t dummy; fixp_t magnitude; FIXP30_polar(a, b, &dummy, &magnitude); return magnitude; } fixp30_t FIXP30_mag(const fixp30_t a, const fixp30_t b) { fixp_t dummy; fixp_t magnitude; FIXP30_polar(a, b, &dummy, &magnitude); return magnitude; } fixp30_t FIXP30_atan2_PU(fixp30_t beta, fixp30_t alpha) { fixp30_t angle_pu; fixp30_t dummy; FIXP30_polar(alpha, beta, &angle_pu, &dummy); return angle_pu; } fixp24_t FIXP24_atan2_PU(fixp24_t beta, fixp24_t alpha) { fixp24_t angle_pu; fixp24_t dummy; FIXP30_polar(alpha, beta, &angle_pu, &dummy); return (angle_pu >> (30 - FIXP_FMT)); } fixp29_t FIXP29_atan2_PU(fixp30_t beta, fixp30_t alpha) { fixp29_t angle_pu; fixp29_t dummy; FIXP30_polar(alpha, beta, &angle_pu, &dummy); return (angle_pu >> (30 - 29)); } fixp_t FIXP_cos(fixp_t angle_rad) { #ifdef FIXPMATH_USE_CORDIC fixp30_t angle_pu = FIXP24_mpy(angle_rad, FIXP30(1.0f/M_TWOPI)); __disable_irq(); WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_COSINE); LL_CORDIC_WriteData(CORDIC, ANGLE_PU_TO_CORDIC(angle_pu)); LL_CORDIC_WriteData(CORDIC, FIXP24(1.0f)); while (HAL_IS_BIT_CLR(CORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ fixp_t data = LL_CORDIC_ReadData(CORDIC); __enable_irq(); return data; #else fixp_t angle_pu = FIXP30_mpy(angle_rad, FIXP30(1.0f/M_TWOPI)); fixp15_t angle_pu_q15 = (angle_pu & (FIXP(1.0f)-1)) >> (FIXP_FMT-15) ; /* Wrap the angle by ANDing, shift to q15 format */ Vector_cossin_s cossin = MATHLIB_cossin(angle_pu_q15); return (cossin.cos << (FIXP_FMT-15)); #endif } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif fixp_t FIXP_cos_PU(fixp_t angle_pu) { #ifdef FIXPMATH_USE_CORDIC __disable_irq(); WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_COSINE); LL_CORDIC_WriteData(CORDIC, ANGLE_FP24_PU_TO_CORDIC(angle_pu)); LL_CORDIC_WriteData(CORDIC, FIXP24(1.0f)); while (HAL_IS_BIT_CLR(CORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ fixp_t data = LL_CORDIC_ReadData(CORDIC); __enable_irq(); return data; #else fixp15_t angle_pu_q15 = (angle_pu & (FIXP(1.0f)-1)) >> (FIXP_FMT-15) ; /* Wrap the angle by ANDing, shift to q15 format */ Vector_cossin_s cossin = MATHLIB_cossin(angle_pu_q15); return (cossin.cos << (FIXP_FMT-15)); #endif } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif fixp30_t FIXP30_cos_PU(fixp30_t angle_pu) { #ifdef FIXPMATH_USE_CORDIC __disable_irq(); WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_COSINE); LL_CORDIC_WriteData(CORDIC, ANGLE_PU_TO_CORDIC(angle_pu)); LL_CORDIC_WriteData(CORDIC, FIXP30(1.0f)); while (HAL_IS_BIT_CLR(CORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ fixp30_t data = LL_CORDIC_ReadData(CORDIC); __enable_irq(); return data; #else fixp_t angle_pu_q15 = (angle_pu & (FIXP30(1.0f)-1)) >> (30-15) ; /* Wrap the angle by ANDing, shift to q15 format */ Vector_cossin_s cossin = MATHLIB_cossin(angle_pu_q15); return (cossin.cos << (30-15)); #endif } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif fixp30_t FIXP30_sin_PU(fixp30_t angle_pu) { #ifdef FIXPMATH_USE_CORDIC __disable_irq(); WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_SINE); LL_CORDIC_WriteData(CORDIC, ANGLE_PU_TO_CORDIC(angle_pu)); LL_CORDIC_WriteData(CORDIC, FIXP30(1.0f)); while (HAL_IS_BIT_CLR(CORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ fixp30_t data = LL_CORDIC_ReadData(CORDIC); __enable_irq(); return data; #else fixp_t angle_pu_q15 = (angle_pu & (FIXP30(1.0f)-1)) >> (30-15) ; /* Wrap the angle by ANDing, shift to q15 format */ Vector_cossin_s cossin = MATHLIB_cossin(angle_pu_q15); return (cossin.sin << (30-15)); #endif } fixp_t FIXP_exp(fixp_t power) { // ToDo: Use CORDIC when supported (The exponential function, exp x, can be obtained as the sum of sinh x and cosh x.) float_t power_flt = FIXP_toF(power); return FIXP((float_t)expf(power_flt)); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section (".ccmram"))) #endif #endif fixp30_t FIXP30_sqrt(const fixp30_t value) { /* Return zero for negative/zero inputs */ if (value <= 0) return 0; #ifdef FIXPMATH_USE_CORDIC_disabled /* Not reliable over the required range yet */ __disable_irq(); WRITE_REG(CORDIC->CSR, CORDIC_CONFIG_SQRT); LL_CORDIC_WriteData(CORDIC, value); while (HAL_IS_BIT_CLR(CORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ fixp30_t data = LL_CORDIC_ReadData(CORDIC); __enable_irq(); return data; #else /* Floating point placeholder calculation */ return FIXP30(sqrtf(FIXP30_toF(value))); #endif } fixp24_t FIXP24_sqrt(const fixp24_t value) { // ToDo: Use CORDIC when supported /* Floating point placeholder calculation */ return FIXP24(sqrtf(FIXP24_toF(value))); } /* end of fixpmath.c */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
14,285
C
31.841379
126
0.636752
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/feed_forward_ctrl.c
/** ****************************************************************************** * @file feed_forward_ctrl.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the Feed-forward * Control 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 FeedForwardCtrl */ /* Includes ------------------------------------------------------------------*/ #include "feed_forward_ctrl.h" #include <stddef.h> #include "mc_type.h" #include "bus_voltage_sensor.h" #include "speed_pos_fdbk.h" #include "speed_torq_ctrl.h" #include "r_divider_bus_voltage_sensor.h" /** @addtogroup MCSDK * @{ */ /** @defgroup FeedForwardCtrl Feed-forward Control * @brief Feed-forward Control component of the Motor Control SDK * * See the [Feed-forward chapter of the User Manual](feed_forward_current_regulation.md) for more details on the theoretical * background of this regulator. * @{ */ /* Private macros ------------------------------------------------------------*/ #define SEGMNUM (uint8_t)7 /* coeff no. -1 */ #define SATURATION_TO_S16(a) if ((a) > 32767) \ { \ (a) = 32767; \ } \ else if ((a) < -32767) \ { \ (a) = -32767; \ } \ else \ {} \ /** * @brief Initializes all the component variables * @param pHandle Feed-forward init structure. * @param pBusSensor VBus Sensor. * @param pPIDId Id PID structure. * @param pPIDIq Iq PID structure. */ __weak void FF_Init(FF_Handle_t *pHandle, BusVoltageSensor_Handle_t *pBusSensor, PID_Handle_t *pPIDId, PID_Handle_t *pPIDIq) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->wConstant_1D = pHandle->wDefConstant_1D; pHandle->wConstant_1Q = pHandle->wDefConstant_1Q; pHandle->wConstant_2 = pHandle->wDefConstant_2; pHandle->pBus_Sensor = pBusSensor; pHandle->pPID_d = pPIDId; pHandle->pPID_q = pPIDIq; #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif } /** * @brief It should be called before each motor start and clears the Feed-forward * internal variables. * @param pHandle Feed-forward structure. */ __weak void FF_Clear(FF_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->Vqdff.q = (int16_t)0; pHandle->Vqdff.d = (int16_t)0; #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif } /** * @brief It implements Feed-forward controller by computing new Vqdff value. * This will be then summed up to PI output in FF_VqdConditioning * method. * @param pHandle Feed-forward structure. * @param Iqdref Iqd reference components used to calculate the Feed-forward * action. * @param pSTC Pointer on speed and torque controller structure. */ __weak void FF_VqdffComputation(FF_Handle_t *pHandle, qd_t Iqdref, SpeednTorqCtrl_Handle_t *pSTC) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif int32_t wtemp1, wtemp2; int16_t hSpeed_dpp; uint16_t hAvBusVoltage_d; SpeednPosFdbk_Handle_t *SpeedSensor; SpeedSensor = STC_GetSpeedSensor(pSTC); hSpeed_dpp = SPD_GetElSpeedDpp(SpeedSensor); hAvBusVoltage_d = VBS_GetAvBusVoltage_d(pHandle->pBus_Sensor) / 2U; if (hAvBusVoltage_d != (uint16_t)0) { /*q-axes ff voltage calculation */ wtemp1 = (((int32_t)(hSpeed_dpp) * Iqdref.d) / (int32_t)32768); wtemp2 = (wtemp1 * pHandle->wConstant_1D) / (int32_t)(hAvBusVoltage_d); wtemp2 *= (int32_t)2; wtemp1 = ((pHandle->wConstant_2 * hSpeed_dpp) / (int32_t)hAvBusVoltage_d) * (int32_t)16; wtemp2 = wtemp1 + wtemp2; SATURATION_TO_S16(wtemp2) pHandle->Vqdff.q = (int16_t)(wtemp2); /* d-axes ff voltage calculation */ wtemp1 = (((int32_t)(hSpeed_dpp) * Iqdref.q) / (int32_t)32768); wtemp2 = (wtemp1 * pHandle->wConstant_1Q) / (int32_t)(hAvBusVoltage_d); wtemp2 *= (int32_t)(-2); SATURATION_TO_S16(wtemp2) pHandle->Vqdff.d = (int16_t)(wtemp2); } else { pHandle->Vqdff.q = (int16_t)0; pHandle->Vqdff.d = (int16_t)0; } #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif } //cstat #MISRAC2012-Rule-2.2_b /* False positive */ #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief It returns the Vqd components computed by input plus the Feed-forward * action and store the last Vqd values in the internal variable. * @param pHandle Feed-forward structure. * @param Vqd Initial value of Vqd to be manipulated by Feed-forward action . * @retval qd_t Vqd conditioned values. */ __weak qd_t FF_VqdConditioning(FF_Handle_t *pHandle, qd_t Vqd) { qd_t lVqd; #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { lVqd.q = 0; lVqd.d = 0; } else { #endif int32_t wtemp; pHandle->VqdPIout = Vqd; wtemp = (int32_t)(Vqd.q) + pHandle->Vqdff.q; SATURATION_TO_S16(wtemp) lVqd.q = (int16_t)wtemp; wtemp = (int32_t)(Vqd.d) + pHandle->Vqdff.d; SATURATION_TO_S16(wtemp) lVqd.d = (int16_t)wtemp; #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif return (lVqd); } #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif /** * @brief It low-pass filters the Vqd voltage coming from the speed PI. Filter * bandwidth depends on hVqdLowPassFilterBW parameter. * @param pHandle Feed-forward structure. */ __weak void FF_DataProcess(FF_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif int32_t wAux; int32_t lowPassFilterBW = (int32_t) pHandle->hVqdLowPassFilterBW - (int32_t)1; #ifndef FULL_MISRA_C_COMPLIANCY_FWD_FDB /* Computation of average Vqd as output by PI(D) current controllers, used by Feed-forward controller algorithm */ wAux = (int32_t)(pHandle->VqdAvPIout.q) * lowPassFilterBW; wAux += pHandle->VqdPIout.q; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 pHandle->VqdAvPIout.q = (int16_t)(wAux >> pHandle->hVqdLowPassFilterBWLOG); wAux = (int32_t)(pHandle->VqdAvPIout.d) * lowPassFilterBW; wAux += pHandle->VqdPIout.d; //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 pHandle->VqdAvPIout.d = (int16_t)(wAux >> pHandle->hVqdLowPassFilterBWLOG); #else /* Computation of average Vqd as output by PI(D) current controllers, used by Feed-forward controller algorithm */ wAux = (int32_t)(pHandle->VqdAvPIout.q) * lowPassFilterBW; wAux += pHandle->VqdPIout.q; pHandle->VqdAvPIout.q = (int16_t)(wAux / (int32_t)(pHandle->hVqdLowPassFilterBW)); wAux = (int32_t)(pHandle->VqdAvPIout.d) * lowPassFilterBW; wAux += pHandle->VqdPIout.d; pHandle->VqdAvPIout.d = (int16_t)(wAux / (int32_t)(pHandle->hVqdLowPassFilterBW)); #endif #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif } /** * @brief Use this method to initialize FF variables in START_TO_RUN state. * @param pHandle Feed-forward structure. */ __weak void FF_InitFOCAdditionalMethods(FF_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->VqdAvPIout.q = 0; pHandle->VqdAvPIout.d = 0; PID_SetIntegralTerm(pHandle->pPID_q, 0); PID_SetIntegralTerm(pHandle->pPID_d, 0); #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif } /** * @brief Use this method to set new constants values used by * Feed-forward algorithm. * @param pHandle Feed-forward structure. * @param sNewConstants The FF_TuningStruct_t containing constants used by * Feed-forward algorithm. */ __weak void FF_SetFFConstants(FF_Handle_t *pHandle, FF_TuningStruct_t sNewConstants) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->wConstant_1D = sNewConstants.wConst_1D; pHandle->wConstant_1Q = sNewConstants.wConst_1Q; pHandle->wConstant_2 = sNewConstants.wConst_2; #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif } //cstat #MISRAC2012-Rule-2.2_b /* False positive */ /** * @brief Use this method to get current constants values used by * Feed-forward algorithm. * @param pHandle Feed-forward structure. * @retval FF_TuningStruct_t Values of the constants used by * Feed-forward algorithm. */ //cstat !MISRAC2012-Rule-8.13 __weak FF_TuningStruct_t FF_GetFFConstants(FF_Handle_t *pHandle) { FF_TuningStruct_t LocalConstants; #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL if (NULL == pHandle) { LocalConstants.wConst_1D = 0; LocalConstants.wConst_1Q = 0; LocalConstants.wConst_2 = 0; } else { #endif LocalConstants.wConst_1D = pHandle->wConstant_1D; LocalConstants.wConst_1Q = pHandle->wConstant_1Q; LocalConstants.wConst_2 = pHandle->wConstant_2; #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL } #endif return (LocalConstants); } /** * @brief Use this method to get present values for the Vqd Feed-forward * components. * @param pHandle Feed-forward structure. * @retval qd_t Vqd Feed-forward components. */ __weak qd_t FF_GetVqdff(const FF_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL qd_t retqt; if (NULL == pHandle) { retqt.q = 0; retqt.d = 0; } else { retqt = pHandle->Vqdff; } return (retqt); #else return (pHandle->Vqdff); #endif } /** * @brief Use this method to get the averaged output values of qd axes * currents PI regulators. * @param pHandle Feed-forward structure. * @retval qd_t Averaged output of qd axes currents PI regulators. */ __weak qd_t FF_GetVqdAvPIout(const FF_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_FEED_FWD_CTRL qd_t retqt; if (NULL == pHandle) { retqt.q = 0; retqt.d = 0; } else { retqt = pHandle->VqdAvPIout; } return (retqt); #else return (pHandle->VqdAvPIout); #endif } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
12,998
C
27.951002
125
0.637329
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/demag_mgt.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 * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "demag_mgt.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** * @defgroup Demag_management Six-Step Demagnetization time management * * @brief Demagnetization time management * * This component is used in applications based on Six-Step algorithm * using either sensorless or sensored position feedback. * * @todo: TODO: complete documentation. * @{ */ /** * @brief It initializes ADC1, DMA and NVIC for three bemf voltages reading * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval none */ __weak void DMG_Init( Demag_Handle_t *pHandle ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->PWMCycles = 0; pHandle->DemagCounterThreshold = pHandle->DemagMinimumThreshold; } } /** * @brief Reset the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval none */ __weak void DMG_Clear( Demag_Handle_t *pHandle ) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->PWMCycles = 0; } } /** * @brief Reset the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval none */ __weak void DMG_IncreaseDemagCounter(Demag_Handle_t *pHandle) { if (MC_NULL == pHandle) { /* Nothing to do */ } else { pHandle->PWMCycles = pHandle->PWMCycles + pHandle->PWMScaling ; } } /** * @brief Reset the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval none */ __weak uint16_t DMG_GetDemagCounter(Demag_Handle_t *pHandle) { return (pHandle->PWMCycles); } /** * @brief Reset the ADC status * @param pHandle: handler of the current instance of the Bemf_ADC component * @retval none */ __weak bool DMG_IsDemagTElapsed(Demag_Handle_t *pHandle ) { bool DemagElapsed = false; if (MC_NULL == pHandle) { /* Nothing to do */ } else { if (pHandle->PWMCycles >= pHandle->DemagCounterThreshold) { DemagElapsed = true; } else { } } return DemagElapsed; } /** * @brief It 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 * @retval none */ __weak void DMG_CalcRevUpDemagT(Demag_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pHandleSTC ) { int16_t hSpeed; SpeednPosFdbk_Handle_t *speedHandle; speedHandle = STC_GetSpeedSensor(pHandleSTC); hSpeed = SPD_GetAvrgMecSpeedUnit(speedHandle); if (hSpeed == 0) { pHandle->DemagCounterThreshold = pHandle->DemagMinimumThreshold;; } else { if (hSpeed < 0) { hSpeed = - hSpeed; } pHandle->DemagCounterThreshold = (uint16_t) (pHandle->RevUpDemagSpeedConv / hSpeed); } if (pHandle->DemagCounterThreshold < pHandle->DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagMinimumThreshold; } } /** * @brief It 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 * @retval none */ __weak void DMG_CalcRunDemagT(Demag_Handle_t *pHandle, SpeednTorqCtrl_Handle_t *pHandleSTC ) { int16_t hSpeed; SpeednPosFdbk_Handle_t *speedHandle; speedHandle = STC_GetSpeedSensor(pHandleSTC); hSpeed = SPD_GetAvrgMecSpeedUnit(speedHandle); if (hSpeed < 0) hSpeed = - hSpeed; if (hSpeed < pHandle->DemagMinimumSpeedUnit) { pHandle->DemagCounterThreshold = (uint16_t) (pHandle->RunDemagSpeedConv / hSpeed); if (pHandle->DemagCounterThreshold < pHandle->DemagMinimumThreshold) { pHandle->DemagCounterThreshold = pHandle->DemagMinimumThreshold; } } else { pHandle->DemagCounterThreshold = pHandle->DemagMinimumThreshold; } } /** * @} */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,514
C
25.38756
94
0.624955
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/open_loop.c
/** ****************************************************************************** * @file open_loop.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the Open Loop 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 OpenLoop */ /* Includes ------------------------------------------------------------------*/ #include "open_loop.h" /** @addtogroup MCSDK * @{ */ /** @defgroup OpenLoop Open Loop Control * @brief Open Loop component of the Motor Control SDK * * Open Loop component allows to run the motor in open loop voltage mode. In that mode, the phase voltages are * forced independently from the measured currents. To do so, the routine OL_VqdConditioning() overwrites the * voltage command Vdq in the FOC current controller task. The voltage level to apply can be set directly by the * user, with OL_UpdateVoltage(), or computed by OL_Calc() if the V/F mode is selected. In that mode, the voltage * level depends on the speed, the slope and the offset selected by the user. * * @{ */ /* Private defines -----------------------------------------------------------*/ /** * @brief Initializes OpenLoop variables.it should be called * once during Motor Control initialization. * @param pHandle: Pointer on Handle structure of OpenLoop feature. * @param pVSS: Pointer on virtual speed sensor structure. */ __weak void OL_Init(OpenLoop_Handle_t *pHandle, VirtualSpeedSensor_Handle_t *pVSS) { #ifdef NULL_PTR_CHECK_OPEN_LOOP if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->hVoltage = pHandle->hDefaultVoltage; pHandle->pVSS = pVSS; #ifdef NULL_PTR_CHECK_OPEN_LOOP } #endif } /** * @brief Sets Vqd according to open loop phase voltage. It should be * called during current controller task. * @param pHandle: Pointer on Handle structure of OpenLoop feature. * @retval qd_t Vqd conditioned values. */ __weak qd_t OL_VqdConditioning(const OpenLoop_Handle_t *pHandle) { qd_t Vqd; Vqd.d = 0; #ifdef NULL_PTR_CHECK_OPEN_LOOP Vqd.q = ((MC_NULL == pHandle) ? 0 : pHandle->hVoltage); #else Vqd.q = (pHandle->hVoltage); #endif return (Vqd); } /** * @brief Sets new open loop phase voltage. * @param pHandle: Pointer on Handle structure of OpenLoop feature. * @param hNewVoltage: New voltage value to apply. */ __weak void OL_UpdateVoltage(OpenLoop_Handle_t *pHandle, int16_t hNewVoltage) { #ifdef NULL_PTR_CHECK_OPEN_LOOP if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->hVoltage = hNewVoltage; #ifdef NULL_PTR_CHECK_OPEN_LOOP } #endif } /** * @brief Gets open loop phase voltage. * @param pHandle: Pointer on Handle structure of OpenLoop feature. */ __weak int16_t OL_GetVoltage(OpenLoop_Handle_t *pHandle) //cstat !MISRAC2012-Rule-8.13 { int16_t hVoltage; #ifdef NULL_PTR_CHECK_OPEN_LOOP hVoltage = ((MC_NULL == pHandle) ? 0 : pHandle->hVoltage); #else hVoltage = pHandle->hVoltage; #endif return (hVoltage); } /** * @brief Computes phase voltage to apply according to average mechanical speed (V/F Mode). * It should be called during background task. * @param pHandle: Pointer on Handle structure of OpenLoop feature. */ __weak void OL_Calc(OpenLoop_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_OPEN_LOOP if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif if (true == pHandle->VFMode) { /* V/F mode true means enabled */ if (pHandle->pVSS->_Super.hAvrMecSpeedUnit >= 0) { pHandle->hVoltage = pHandle->hVFOffset + (pHandle->hVFSlope * pHandle->pVSS->_Super.hAvrMecSpeedUnit); } else { pHandle->hVoltage = pHandle->hVFOffset - (pHandle->hVFSlope * pHandle->pVSS->_Super.hAvrMecSpeedUnit); } } else { /* Nothing to do */ } #ifdef NULL_PTR_CHECK_OPEN_LOOP } #endif } /** * @brief Activates of the Voltage versus Frequency mode (V/F mode). * @param pHandle: Pointer on Handle structure of OpenLoop feature. * @param VFEnabling: Flag to enable the V/F mode. */ __weak void OL_VF(OpenLoop_Handle_t *pHandle, bool VFEnabling) { #ifdef NULL_PTR_CHECK_OPEN_LOOP if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif pHandle->VFMode = VFEnabling; #ifdef NULL_PTR_CHECK_OPEN_LOOP } #endif } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,116
C
26.363636
115
0.606919
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/max_torque_per_ampere.c
/** ****************************************************************************** * @file max_torque_per_ampere.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the features * of the Maximum Torque Per Ampere (MTPA) Control component of the Motor Control SDK: * * * Initialize the parameter for MTPA * * Calculate and output id and iq reference based on torque input * * Calculate and output id based on iq input * ****************************************************************************** * @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 MTPA */ /* Includes ------------------------------------------------------------------*/ #include "max_torque_per_ampere.h" #include <stdint.h> /** @addtogroup MCSDK * @{ */ /** @defgroup MTPA Maximum Torque Per Ampere Control * @brief Maximum Torque Per Ampere (MTPA) Control component of the Motor Control SDK * * The torque of the PMSM can be expressed with the equation shown below: * * @f[ * T_e = \frac{3}{2}\times p \times \phi \times i_q + \frac{3}{2}\times p\times(L_d-L_q)\times i_q\times i_d * @f] * * When the motor is a surface mount permanent magnet synchronous motor (SM-PMSM), the @f$ L_d @f$ and @f$ L_q @f$ * are almost the same, so only the @f$ i_q @f$ can influence the torque. For internal permanent * magnet synchronous motor (I-PMSM), the @f$ L_d @f$ is not equal to @f$ L_q @f$. Both @f$ i_d @f$ and @f$ i_q @f$ will influence * the torque. * The aim of the MTPA (maximum-torque-per-ampere) control is to calculate the * reference currents which maximize the ratio between produced * electromagnetic torque and copper losses. * The input of this component * is the @f$ i_q @f$ reference. The output of this component is @f$ i_d @f$ reference. * * @{ */ /** * @brief Calculates the Id current reference based on input Iq current reference * @param pHandle Handle on the MTPA component * @param Iqdref current reference in the Direct-Quadratic reference frame. Expressed * in the qd_t format. * */ __weak void MTPA_CalcCurrRefFromIq(const MTPA_Handle_t *pHandle, qd_t *Iqdref) { #ifdef NULL_PTR_CHECK_MAX_TRQ_PER_AMP if ((NULL == pHandle) || (NULL == Iqdref)) { /* Nothing to do */ } else { #endif int32_t id; int16_t aux; int16_t iq; uint8_t segment; iq = ((Iqdref->q < 0) ? (-Iqdref->q) : (Iqdref->q)); /* Teref absolute value */ aux = iq / pHandle->SegDiv; segment = (uint8_t)aux; if (segment > SEGMENT_NUM) { segment = SEGMENT_NUM; } else { /* Nothing to do */ } #ifndef FULL_MISRA_C_COMPLIANCY_MAX_TOR //cstat !MISRAC2012-Rule-1.3_n !ATH-shift-neg !MISRAC2012-Rule-10.1_R6 id = ((pHandle->AngCoeff[segment] * iq) >> 15) + pHandle->Offset[segment]; #else id = ((pHandle->AngCoeff[segment] * iq) / 32768) + pHandle->Offset[segment]; #endif Iqdref->d = (int16_t)id; #ifdef NULL_PTR_CHECK_MAX_TRQ_PER_AMP } #endif } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,485
C
38.467626
132
0.64175
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/cmd_parser.c
/** ****************************************************************************** * @file register_interface.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the register access for the MCP protocol * * ****************************************************************************** * @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 * ****************************************************************************** */ #include "stdint.h" #include "string.h" #include "register_interface.h" #include "mc_config.h" #include "mc_parameters.h" #include "mcp.h" #include "mcp_config.h" #include "mcpa.h" #include "mc_configuration_registers.h" //#include "dac_ui.h" __weak uint8_t RI_SetRegCommandParser (MCP_Handle_t * pHandle, uint16_t txSyncFreeSpace) { uint16_t * dataElementID; uint8_t * rxData = pHandle->rxBuffer; uint8_t * txData = pHandle->txBuffer; int16_t rxLength = pHandle->rxLength; uint16_t size; uint8_t retVal=MCP_CMD_OK; uint8_t accessResult; uint8_t number_of_item =0; pHandle->txLength = 0; while (rxLength > 0) { number_of_item ++; dataElementID = (uint16_t *) rxData; rxLength = rxLength-MCP_ID_SIZE; // We consume 2 byte in the DataID rxData = rxData+MCP_ID_SIZE; // Shift buffer to the next data accessResult = RI_SetReg (*dataElementID,rxData,&size,rxLength); /* Prepare next data*/ rxLength = (int16_t) (rxLength - size); rxData = rxData+size; /* If there is only one CMD in the buffer, we do not store the result */ if (number_of_item == 1 && rxLength == 0) { retVal = accessResult; } else {/* Store the result for each access to be able to report failling access */ if (txSyncFreeSpace !=0 ) { *txData = accessResult; txData = txData+1; pHandle->txLength++; txSyncFreeSpace--; /* decrement one by one no wraparound possible */ retVal = (accessResult != MCP_CMD_OK) ? MCP_CMD_NOK : retVal; if ((accessResult == MCP_ERROR_BAD_DATA_TYPE) || (accessResult == MCP_ERROR_BAD_RAW_FORMAT)) { /* From this point we are not able to continue to decode CMD buffer*/ /* We stop the parsing */ rxLength = 0; } } else { /* Stop parsing the cmd buffer as no space to answer */ /* If we reach this state, chances are high the command was badly formated or received */ rxLength = 0; retVal = MCP_ERROR_NO_TXSYNC_SPACE; } } } /* If all accesses are fine, just one global MCP_CMD_OK is required*/ if (retVal == MCP_CMD_OK) { pHandle->txLength = 0; } return retVal; } __weak uint8_t RI_GetRegCommandParser (MCP_Handle_t * pHandle, uint16_t txSyncFreeSpace) { uint16_t * dataElementID; uint8_t * rxData = pHandle->rxBuffer; uint8_t * txData = pHandle->txBuffer; uint16_t size = 0; uint16_t rxLength = pHandle->rxLength; int16_t freeSpaceS16 = (int16_t) txSyncFreeSpace; uint8_t retVal = MCP_CMD_NOK; pHandle->txLength = 0; while (rxLength > 0) { dataElementID = (uint16_t *) rxData; rxLength = rxLength-MCP_ID_SIZE; rxData = rxData+MCP_ID_SIZE; // Shift buffer to the next MCP_ID retVal = RI_GetReg (*dataElementID,txData, &size, freeSpaceS16); if (retVal == MCP_CMD_OK ) { txData = txData+size; pHandle->txLength += size; freeSpaceS16 = freeSpaceS16-size; } else { rxLength = 0; } } return retVal; }
3,935
C
31.262295
106
0.587802
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/circle_limitation.c
/** ****************************************************************************** * @file circle_limitation.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides the functions that implement the circle * limitation feature of the STM32 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 */ /* Includes ------------------------------------------------------------------*/ #include "circle_limitation.h" #include "mc_math.h" #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @defgroup CircleLimitation Circle Limitation * @brief Circle Limitation component of the Motor Control SDK * * @{ */ #if defined (CCMRAM) #if defined (__ICCARM__) #pragma location = ".ccmram" #elif defined (__CC_ARM) || defined(__GNUC__) __attribute__((section(".ccmram"))) #endif #endif #if defined CIRCLE_LIMITATION_SQRT_M0 const uint16_t SqrtTable[1025] = SQRT_CIRCLE_LIMITATION; #endif /** * @brief Returns the saturated @f$v_q, v_d@f$ component values * @param pHandle Handler of the CircleLimitation component * @param Vqd @f$v_q, v_d@f$ values * @retval Saturated @f$v_q, v_d@f$ values * * This function implements the CircleLimitation feature described CircleLimitation component. * * @f$v_d = \min(v_d^*, v_d MAX) @f$ * * @f$v_q = \sqrt(MaxModule^2-v_d^2\ ) @f$ * */ __weak qd_t Circle_Limitation(const CircleLimitation_Handle_t *pHandle, qd_t Vqd) { qd_t local_vqd = Vqd; #ifdef NULL_PTR_CHECK_CRC_LIM if (MC_NULL == pHandle) { local_vqd.q = 0; local_vqd.d = 0; } else { #endif int32_t maxModule; int32_t square_q; int32_t square_temp; int32_t square_d; int32_t square_sum; int32_t square_limit; int32_t vd_square_limit; int32_t new_q; int32_t new_d; maxModule = (int32_t)pHandle->MaxModule; square_q = ((int32_t)(Vqd.q)) * Vqd.q; square_d = ((int32_t)(Vqd.d)) * Vqd.d; square_limit = maxModule * maxModule; vd_square_limit = ((int32_t)pHandle->MaxVd) * ((int32_t)pHandle->MaxVd); square_sum = square_q + square_d; if (square_sum > square_limit) { if (square_d <= vd_square_limit) { #if defined CIRCLE_LIMITATION_SQRT_M0 square_temp = (square_limit - square_d) / 1048576; new_q = SqrtTable[square_temp]; #else square_temp = square_limit - square_d; new_q = MCM_Sqrt(square_temp); #endif if (Vqd.q < 0) { new_q = -new_q; } else { /* Nothing to do */ } new_d = Vqd.d; } else { new_d = (int32_t)pHandle->MaxVd; if (Vqd.d < 0) { new_d = -new_d; } else { /* Nothing to do */ } #if defined CIRCLE_LIMITATION_SQRT_M0 square_temp = (square_limit - vd_square_limit) / 1048576; new_q = SqrtTable[square_temp]; #else square_temp = square_limit - vd_square_limit; new_q = MCM_Sqrt(square_temp); #endif if (Vqd.q < 0) { new_q = - new_q; } else { /* Nothing to do */ } } local_vqd.q = (int16_t)new_q; local_vqd.d = (int16_t)new_d; } #ifdef NULL_PTR_CHECK_CRC_LIM } #endif return (local_vqd); } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
3,984
C
23.90625
95
0.525602
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Src/mcpa.c
/****************************************************************************** * @file mcpa.c * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the datalog feature * of the MCP protocol * * ****************************************************************************** * @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 * ****************************************************************************** */ #include "mc_type.h" #include "string.h" #include "mcp.h" #include "register_interface.h" #include "mcpa.h" uint32_t GLOBAL_TIMESTAMP = 0U; static void MCPA_stopDataLog(MCPA_Handle_t *pHandle); /** @addtogroup MCSDK * @{ */ /** @addtogroup MCP * @{ */ /** * @brief Allocates and fills buffer with asynchronous data to be sent to controller * * @param *pHandle Pointer to the MCPA Handle */ void MCPA_dataLog(MCPA_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_MCPA if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif uint32_t *logValue; uint16_t *logValue16; uint8_t i; if (pHandle->HFIndex == pHandle->HFRateBuff) /* */ { pHandle->HFIndex = 0U; if (0U == pHandle->bufferIndex) { /* New buffer allocation */ if (0U == pHandle->pTransportLayer->fGetBuffer (pHandle->pTransportLayer, (void **) &pHandle->currentBuffer, //cstat !MISRAC2012-Rule-11.3 MCTL_ASYNC)) { /* Nothing to do, try next HF Task to get an Async buffer */ #ifdef MCP_DEBUG_METRICS pHandle->bufferMissed++; #endif } else { logValue = (uint32_t *)pHandle->currentBuffer; //cstat !MISRAC2012-Rule-11.3 *logValue = GLOBAL_TIMESTAMP; /* 32 first bits is used to store Timestamp */ pHandle->bufferIndex = 4U; pHandle->MFIndex = 0U; /* Restart the motif from scratch at each buffer */ /* Check if configuration has changed for this new buffer */ if (pHandle->Mark == pHandle->MarkBuff) { /* Nothing to do */ } else { pHandle->MarkBuff = pHandle->Mark; pHandle->HFNumBuff = pHandle->HFNum; pHandle->MFNumBuff = pHandle->MFNum; pHandle->HFRateBuff = pHandle->HFRate; pHandle->MFRateBuff = pHandle->MFRate; pHandle->bufferTxTriggerBuff = pHandle->bufferTxTrigger; /* We store pointer here, so 4 bytes */ (void)memcpy(pHandle->dataPtrTableBuff, pHandle->dataPtrTable, ((uint32_t)pHandle->HFNum + (uint32_t)pHandle->MFNum) * 4U); /* We store pointer here, so 4 bytes */ (void)memcpy(pHandle->dataSizeTableBuff, pHandle->dataSizeTable, (uint32_t)pHandle->HFNum + (uint32_t)pHandle->MFNum); /* 1 size byte per ID */ } } } else { /* Nothing to do */ } /* */ if ((pHandle->bufferIndex > 0U) && (pHandle->bufferIndex <= pHandle->bufferTxTriggerBuff)) { logValue16 = (uint16_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; //cstat !MISRAC2012-Rule-11.3 for (i = 0U; i < pHandle->HFNumBuff; i++) { *logValue16 = *((uint16_t *) pHandle->dataPtrTableBuff[i]) ; //cstat !MISRAC2012-Rule-11.5 logValue16++; pHandle->bufferIndex = pHandle->bufferIndex + 2U; } /* MFRateBuff=254 means we dump MF data once per buffer */ /* MFRateBuff=255 means we do not dump MF data */ if (pHandle->MFRateBuff < 254U) { if (pHandle->MFIndex == pHandle->MFRateBuff) { pHandle->MFIndex = 0U; for (i = pHandle->HFNumBuff; i < (pHandle->MFNumBuff + pHandle->HFNumBuff); i++) { /* Dump MF data */ logValue = (uint32_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; //cstat !MISRAC2012-Rule-11.3 *logValue = *((uint32_t *)pHandle->dataPtrTableBuff[i]); //cstat !MISRAC2012-Rule-11.5 #ifdef NOT_IMPLEMENTED /* Code not implemented. */ switch (pHandle->dataSizeTableBuff[i]) { case 1: { logValue8 = (uint8_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; *logValue8 = *((uint8_t *)pHandle->dataPtrTableBuff[i]); break; } case 2: { logValue16 = (uint16_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; *logValue16 = *((uint16_t *)pHandle->dataPtrTableBuff[i]); break; } case 4: { logValue32 = (uint32_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; *logValue32 = *((uint32_t *)pHandle->dataPtrTableBuff[i]); break; } default: break; } #endif pHandle->bufferIndex = pHandle->bufferIndex+pHandle->dataSizeTableBuff[i]; } } else { pHandle->MFIndex ++; } } else { /* Nothing to do */ } } else { /* Nothing to do */ } if (pHandle->bufferIndex > pHandle->bufferTxTriggerBuff) { if (pHandle->MFRateBuff == 254U) /* MFRateBuff = 254 means we dump MF data once per buffer */ { for (i = pHandle->HFNumBuff; i < (pHandle->MFNumBuff + pHandle->HFNumBuff); i++) { logValue = (uint32_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; //cstat !MISRAC2012-Rule-11.3 *logValue = *((uint32_t *)pHandle->dataPtrTableBuff[i]); //cstat !MISRAC2012-Rule-11.5 pHandle->bufferIndex = pHandle->bufferIndex + pHandle->dataSizeTableBuff[i]; } } else { /* Nothing to do */ } /* Buffer is ready to be send */ logValue16 = (uint16_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; //cstat !MISRAC2012-Rule-11.3 *logValue16 = pHandle->MarkBuff; /* MarkBuff is actually 8 bits, but we add also 8 bits of the ASYNCID=0 after the MARK. */ pHandle->pTransportLayer->fSendPacket(pHandle->pTransportLayer, pHandle->currentBuffer, pHandle->bufferIndex + 2U, MCTL_ASYNC); pHandle->bufferIndex = 0U; } else { /* Nothing to do */ } } else { /* Nothing to log just waiting next call to MCPA_datalog */ pHandle->HFIndex++; } #ifdef NULL_PTR_CHECK_MCPA } #endif } /** * @brief Sends asynchronous data to controller when the buffer is full * * @param *pHandle Pointer to the MCPA Handle */ void MCPA_flushDataLog (MCPA_Handle_t *pHandle) { #ifdef NULL_PTR_CHECK_MCPA if (MC_NULL == pHandle) { /* Nothing to do */ } else { #endif uint32_t *logValue; uint16_t *logValue16; uint8_t i; if (pHandle->bufferIndex > 0U) { /* If buffer is allocated, we must send it */ if (pHandle->MFRateBuff == 254U) /* In case of flush, we must respect the packet format to allow proper decoding */ { for (i = pHandle->HFNumBuff; i < (pHandle->MFNumBuff + pHandle->HFNumBuff); i++) { logValue = (uint32_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; //cstat !MISRAC2012-Rule-11.3 *logValue = *((uint32_t *)pHandle->dataPtrTableBuff[i]); //cstat !MISRAC2012-Rule-11.5 pHandle->bufferIndex = pHandle->bufferIndex+pHandle->dataSizeTableBuff[i]; } } else { /* Nothing to do */ } logValue16 = (uint16_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; //cstat !MISRAC2012-Rule-11.3 *logValue16 = pHandle->MarkBuff; /* MarkBuff is actually 8 bits, but we add also 8 bits of the ASYNCID=0 after the MARK */ pHandle->pTransportLayer->fSendPacket (pHandle->pTransportLayer, pHandle->currentBuffer, pHandle->bufferIndex + 2U, MCTL_ASYNC); pHandle->bufferIndex = 0U; } else { /* Nothing to do */ } #ifdef NULL_PTR_CHECK_MCPA } #endif } /** * @brief Stops the asynchronous communication * * @param *pHandle Pointer to the MCPA Handle */ void MCPA_stopDataLog(MCPA_Handle_t *pHandle) { uint16_t *logValue16; pHandle->Mark = 0U; if (pHandle->bufferIndex > 0U) { /* If buffer is allocated, we must send it */ logValue16 = (uint16_t *)&pHandle->currentBuffer[pHandle->bufferIndex]; //cstat !MISRAC2012-Rule-11.3 *logValue16 = pHandle->MarkBuff; /* MarkBuff is actually 8 bits, but we add also 8 bits of the ASYNCID=0 after the MARK */ pHandle->pTransportLayer->fSendPacket (pHandle->pTransportLayer, pHandle->currentBuffer, pHandle->bufferIndex + 2U, MCTL_ASYNC); } else { /* Nothing to do */ } pHandle->bufferIndex = 0U; pHandle->MarkBuff = 0U; pHandle->HFIndex = 0U; pHandle->HFRateBuff = 0U; /* We do not want to miss any sample at the restart */ } /** * @brief Stores the asynchronous configuration stating all the register to be continuously sent to controller * * @param *pHandle Pointer to the MCPA Handle * @param *cfgdata Configuration of the Async communication */ uint8_t MCPA_cfgLog(MCPA_Handle_t *pHandle, uint8_t *cfgdata) { uint8_t result = MCP_CMD_OK; #ifdef NULL_PTR_CHECK_MCPA if (MC_NULL == pHandle) { result = MCP_CMD_NOK; } else { #endif uint8_t i; uint16_t logSize = 0U; /* Max size of a log per iteration (HF+MF) */ uint16_t newID, buffSize; uint8_t *pCfgData = cfgdata; buffSize = *((uint16_t *)pCfgData); //cstat !MISRAC2012-Rule-11.3 if (buffSize == 0U) { /* Switch Off condition */ MCPA_stopDataLog(pHandle); } else if (buffSize > pHandle->pTransportLayer->txAsyncMaxPayload) { result = MCP_ERROR_NO_TXASYNC_SPACE; } else { pHandle->HFRate = *((uint8_t *)&pCfgData[2]); pHandle->HFNum = *((uint8_t *)&pCfgData[3]); pHandle->MFRate = *((uint8_t *)&pCfgData[4]); pHandle->MFNum = *((uint8_t *)&pCfgData[5]); pCfgData = &pCfgData[6]; /* Start of the HF IDs */ if ((pHandle->HFNum + pHandle->MFNum) <= pHandle->nbrOfDataLog) { for (i = 0; i < (pHandle->HFNum + pHandle->MFNum); i++) { newID = *((uint16_t *)pCfgData); //cstat !MISRAC2012-Rule-11.3 (void)RI_GetPtrReg(newID, &pHandle->dataPtrTable[i]); /* HF Data are fixed to 2 bytes */ pHandle->dataSizeTable[i] = (i < pHandle->HFNum ) ? 2U : RI_GetIDSize(newID); pCfgData++; /* Point to the next UID */ pCfgData++; logSize = logSize+pHandle->dataSizeTable[i]; } /* Smallest packet must be able to contain logSize Markbyte AsyncID and TimeStamp */ if (buffSize < (logSize + 2U + 4U)) { result = MCP_ERROR_NO_TXASYNC_SPACE; } else { pHandle->bufferTxTrigger = buffSize-logSize - 2U; /* 2 is required to add the last Mark byte and NUL ASYNCID */ pHandle->Mark = *((uint8_t *)pCfgData); if (0U == pHandle->Mark) { /* Switch Off condition */ MCPA_stopDataLog(pHandle); } else { /* Nothing to do */ } } } else { result = MCP_ERROR_BAD_RAW_FORMAT; } } #ifdef NULL_PTR_CHECK_MCPA } #endif return (result); } /** * @} */ /** * @} */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
12,669
C
31.909091
119
0.530271
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pwm_common_sixstep.h
/** ****************************************************************************** * @file pwm_common_sixstep.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * six-step PWM 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 pwm_curr_fdbk_6s */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef PWMNCOMMON_SIXSTEP_H #define PWMNCOMMON_SIXSTEP_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #define NB_CONVERSIONS 16u #define S16_120_PHASE_SHIFT (int16_t)(65536/3) #define S16_60_PHASE_SHIFT (int16_t)(65536/6) /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @addtogroup pwm_curr_fdbk_6s * @{ */ /* Exported defines ------------------------------------------------------------*/ #define STEP_1 0U #define STEP_2 1U #define STEP_3 2U #define STEP_4 3U #define STEP_5 4U #define STEP_6 5U /* Exported defines ----------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /** @brief PWMC component handle type */ typedef struct PWMC_Handle PWMC_Handle_t; //cstat !MISRAC2012-Rule-2.4 /** * @brief Pointer on callback functions used by PWMC components * * This type is needed because the actual functions to use can change at run-time. * * See the following items: * - PWMC_Handle::pFctSwitchOffPwm * - PWMC_Handle::pFctSwitchOnPwm * * */ typedef void (*PWMC_Generic_Cb_t)(PWMC_Handle_t *pHandle); /** * @brief Pointer on the function provided by the PMWC component instance to set low sides ON. * * This type is needed because the actual function to use can change at run-time * (See PWMC_Handle::pFctTurnOnLowSides). * */ typedef void (*PWMC_TurnOnLowSides_Cb_t)(PWMC_Handle_t *pHandle, const uint32_t ticks); /** * @brief Pointer on the function provided by the PMWC component instance to set the trigger point * of the ADC. * * This type is needed because the actual function to use can change at run-time * (See PWMC_Handle::pFctOCPSetReferenceVoltage). * */ typedef void (*PWMC_SetADCTriggerChannel_Cb_t)(PWMC_Handle_t *pHandle, uint16_t hDACVref); /** * @brief Pointer on the function provided by the PMWC component instance to check if an over current * condition has occured. * * This type is needed because the actual function to use can change at run-time * (See PWMC_Handle::pFctIsOverCurrentOccurred). * */ typedef uint16_t (*PWMC_OverCurr_Cb_t)(PWMC_Handle_t *pHandle); /** * @brief Pointer on the function provided by the PMWC component instance to check optional * modulation features flag (fast demagnetization and quasi-synchronous rectification) * */ typedef uint8_t (*PWMC_ModFlag_Cb_t)(PWMC_Handle_t *pHandle); /** * @brief This structure is used to handle the status change of optional modulation features * */ typedef enum { NO_REQUEST, ENABLE_FAST_DEMAG, DISABLE_FAST_DEMAG, ENABLE_QUASI_SYNCH, DISABLE_QUASI_SYNCH } PWMTableUpdate_t; /** * @brief This structure is used to handle the data of an instance of the PWM component * */ struct PWMC_Handle { /** @{ */ PWMC_Generic_Cb_t pFctSwitchOffPwm; /**< pointer on the function the component instance used to switch PWM off */ PWMC_Generic_Cb_t pFctSwitchOnPwm; /**< pointer on the function the component instance used to switch PWM on */ PWMC_SetADCTriggerChannel_Cb_t /**< pointer on the function the component instance used to set the trigger point of the ADC */ pFctSetADCTriggerChannel; PWMC_TurnOnLowSides_Cb_t pFctTurnOnLowSides; /**< pointer on the function the component instance used to turn low sides on */ PWMC_OverCurr_Cb_t pFctIsOverCurrentOccurred; /**< pointer on the fct the component instance used to return the over current status */ PWMC_ModFlag_Cb_t pGetFastDemagFlag; /**< pointer on the fct the component instance used to return the fast demag status */ PWMC_ModFlag_Cb_t pGetQuasiSynchFlag; /**< pointer on the fct the component instance used to return the quasi-Synch rectification status */ /** @} */ uint16_t CntPh; /**< PWM Duty cycle phase*/ uint16_t StartCntPh; /**< Start-up PWM Duty cycle phase*/ uint16_t ADCTriggerCnt; /**< Timer output trigger point used for ADC triggering */ uint16_t SWerror; /**< Contains status about SW error */ uint16_t PWMperiod; /**< PWM period expressed in timer clock cycles unit: * @f$hPWMPeriod = TimerFreq_{CLK} / F_{PWM}@f$ */ uint16_t DTCompCnt; /**< Half of Dead time expressed * in timer clock cycles unit: * @f$hDTCompCnt = (DT_s \cdot TimerFreq_{CLK})/2@f$ */ uint8_t Motor; /**< Motor reference number */ int16_t AlignFlag; /*!< phase current 0 is reliable, 1 is bad */ uint8_t NextStep; /**< Step number to be applied the step number */ uint8_t Step; /**< Step number */ uint16_t DemagCounterThreshold; int16_t hElAngle; bool OverCurrentFlag; /*!< This flag is set when an overcurrent occurs.*/ bool OverVoltageFlag; /*!< This flag is set when an overvoltage occurs.*/ bool BrakeActionLock; /*!< This flag is set to avoid that brake action is * interrupted.*/ bool driverProtectionFlag; bool TurnOnLowSidesAction; /**< true if TurnOnLowSides action is active, false otherwise. */ PWMTableUpdate_t ModUpdateReq; /**< Request flag of optional modulation features status */ }; /* Exported functions --------------------------------------------------------*/ /* Switches the PWM generation off, setting the outputs to inactive */ void PWMC_SwitchOffPWM(PWMC_Handle_t *pHandle); /* Switches the PWM generation on */ void PWMC_SwitchOnPWM(PWMC_Handle_t *pHandle); /* Set the trigger instant of the ADC for Bemf acquisition*/ void PWMC_SetADCTriggerChannel( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ); /* Turns low sides on. 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. */ void PWMC_TurnOnLowSides(PWMC_Handle_t * pHandle, uint32_t ticks); /* Retrieves the status of the "TurnOnLowSides" action. */ bool PWMC_GetTurnOnLowSidesAction( PWMC_Handle_t * pHandle ); /* It is used to set the align motor flag.*/ void PWMC_SetAlignFlag(PWMC_Handle_t *pHandle, int16_t flag); /* Sets the Callback that the PWMC component shall invoke to switch off PWM * generation. */ void PWMC_RegisterSwitchOffPwmCallBack(PWMC_Generic_Cb_t pCallBack, PWMC_Handle_t *pHandle); /* Sets the Callback that the PWMC component shall invoke to switch on PWM * generation. */ void PWMC_RegisterSwitchonPwmCallBack(PWMC_Generic_Cb_t pCallBack, PWMC_Handle_t *pHandle); /* Sets the Callback that the PWMC component shall invoke to turn on low sides. */ void PWMC_RegisterTurnOnLowSidesCallBack(PWMC_TurnOnLowSides_Cb_t pCallBack, PWMC_Handle_t *pHandle); /* Sets the Callback that the PWMC component shall invoke to the over current status. */ void PWMC_RegisterIsOverCurrentOccurredCallBack(PWMC_OverCurr_Cb_t pCallBack, PWMC_Handle_t *pHandle); /* It is used to clear the variable in CPWMC. */ void PWMC_Clear(PWMC_Handle_t *pHandle); /* It forces the Fast Demag interval to the passed value */ void PWMC_ForceFastDemagTime(PWMC_Handle_t * pHdl, uint16_t constFastDemagTime ); /* It enables/disables the Fast Demag feature */ void PWMC_SetFastDemagState(PWMC_Handle_t * pHandle, uint8_t State ); /* It enables/disables the Qusi Synch feature */ void PWMC_SetQuasiSynchState(PWMC_Handle_t * pHandle, uint8_t State ); /* It returns the Fast Demag feature status */ uint8_t PWMC_GetFastDemagState(PWMC_Handle_t * pHandle ); /* It returns the Quasi Synch feature status */ uint8_t PWMC_GetQuasiSynchState(PWMC_Handle_t * pHandle ); /* It converts the motor electrical angle to the corresponding step in the six-step sequence */ uint8_t PWMC_ElAngleToStep( PWMC_Handle_t * pHandle ); /* Checks if an overcurrent occurred since last call. */ uint16_t PWMC_IsFaultOccurred(PWMC_Handle_t *pHandle); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* PWMNCOMMON_SIXSTEP_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
9,824
C
37.378906
144
0.61024
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pwmc_6pwm.h
/** ****************************************************************************** * @file pwmc_6pwm.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * pwmc_6pwm 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_6pwm */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __PWMC_6PWM_H #define __PWMC_6PWM_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "pwm_common_sixstep.h" /** * @addtogroup MCSDK * @{ */ /** * @addtogroup pwm_curr_fdbk_6s * @{ */ /** * @addtogroup pwmc_6pwm * @{ */ /* Exported constants --------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /** * @brief R3_F0XX 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; /*!< Current channel output polarity.*/ uint32_t OCNPolarity; /*!< Current complementary channel output polarity. */ } SixPwm_Params_t; /** * @brief Handle structure of the r1_f0xx_pwm_curr_fdbk Component */ typedef struct { PWMC_Handle_t _Super; /*!< Offset of current sensing network */ bool QuasiSynchDecay; /*!< This flag is set when the quasi-synchronous decay is activated.*/ 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; SixPwm_Params_t const * pParams_str; } PWMC_SixPwm_Handle_t; /* Exported functions ------------------------------------------------------- */ /** * It initializes TIMx and NVIC */ void SixPwm_Init( PWMC_SixPwm_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 SixPwm_LoadNextStep( PWMC_SixPwm_Handle_t * pHandle, int16_t Direction ); /** * It uploads the duty cycle into timer registers. */ bool SixPwm_ApplyNextStep( PWMC_SixPwm_Handle_t * pHandle ); /** * It uploads the duty cycle into timer registers. */ bool SixPwm_IsFastDemagUpdated( PWMC_SixPwm_Handle_t * pHandle ); /** * It resets the polarity of the timer PWM channel outputs to default */ void SixPwm_ResetOCPolarity( PWMC_SixPwm_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 SixPwm_TurnOnLowSides( PWMC_Handle_t * pHdl, uint32_t ticks); /** * This function enables the PWM outputs */ void SixPwm_SwitchOnPWM( PWMC_Handle_t * pHdl ); /** * It disables PWM generation on the proper Timer peripheral acting on * MOE bit and reset the TIM status */ void SixPwm_SwitchOffPWM( PWMC_Handle_t * pHdl ); /** * It sets the capcture compare of the timer channel used for ADC triggering */ void SixPwm_SetADCTriggerChannel( PWMC_Handle_t * pHdl, uint16_t SamplingPoint ); /** * It is used to check if an overcurrent occurred since last call. */ uint16_t SixPwm_IsOverCurrentOccurred( PWMC_Handle_t * pHdl ); /** * It contains the Break event interrupt */ void * SixPwm_BRK_IRQHandler( PWMC_SixPwm_Handle_t * pHandle ); /** * It is used to return the fast demag flag. */ uint8_t SixPwm_FastDemagFlag( PWMC_Handle_t * pHdl ); /** * It is used to return the quasi-synchronous rectification flag. */ uint8_t SixPwm_QuasiSynchFlag( PWMC_Handle_t * pHdl ); /** * It increases the demagnetization counter in the update event. */ void SixPwm_UpdatePwmDemagCounter( PWMC_SixPwm_Handle_t * pHandle ); /** * It disables the update event and the updated of the demagnetization counter. */ void SixPwm_DisablePwmDemagCounter( PWMC_SixPwm_Handle_t * pHandle ); /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*__PWMC_6PWM_H*/ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,635
C
29.301075
115
0.587578
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mcpa.h
/** ****************************************************************************** * @file mcpa.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the Datalog * 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 MCPA_H #define MCPA_H #include "mcptl.h" extern uint32_t GLOBAL_TIMESTAMP; /** @addtogroup MCSDK * @{ */ /** @addtogroup MCP * @{ */ /** * @brief MCP asynchronous parameters handle. * * Defined differently depending on the UART used. * */ typedef struct { MCTL_Handle_t *pTransportLayer; /** Pointer to the transport layer structure, containing Performer capabilities. */ void ** dataPtrTable; /** Table of pointers to the value to be returned. */ void ** dataPtrTableBuff; /** Buffered version of dataPtrTable. */ uint8_t *dataSizeTable; /** Table containing the sizes of the values to be returned.*/ uint8_t *dataSizeTableBuff; /** Buffered version of dataSizeTable. */ uint8_t *currentBuffer; /** Current buffer allocated. */ uint16_t bufferIndex; /** Index of the position inside the bufer, a new buffer is allocated when bufferIndex = 0. */ uint16_t bufferTxTrigger; /** Threshold upon which data is dumped. */ uint16_t bufferTxTriggerBuff; /** Buffered version of bufferTxTrigger. */ #ifdef MCP_DEBUG_METRICS uint16_t bufferMissed; /** Incremented each time a buffer is missed. Debug only. */ #endif uint8_t nbrOfDataLog; /** Total number of values the performer is able to send at once. */ uint8_t HFIndex; /** Incremental value going from 0 to HFRateBuff, data is dump when HFRateBuff is reached. Incremented every HFT. */ uint8_t MFIndex; /** Incremental value going from 0 to MFRateBuff, data is dump when MFRateBuff is reached with an exception made for MFRateBuff == 254. Incremented every MFT.*/ uint8_t HFRate; /** Rate at which HF data is dumped. 0 means every HFT, 1 means 1 in 2. */ uint8_t HFRateBuff; /** Buffered version of HFRate. */ uint8_t HFNum; /** Number of HF values to be returned. */ uint8_t HFNumBuff; /** Buffered version of HFNum. */ uint8_t MFRate; /** Rate at which MF data is dumped. 254 means once per buffer, 255 means MF data is not dumped. */ uint8_t MFRateBuff; /** Buffered version of MFRate. */ uint8_t MFNum; /** Number of MF values to be returned. */ uint8_t MFNumBuff; /** Buffered version of MFNum. */ uint8_t Mark; /** Configuration of the ASYNC communication. */ uint8_t MarkBuff; /** Buffered version of Mark. */ } MCPA_Handle_t; /* MCP Async handle type */ void MCPA_dataLog(MCPA_Handle_t *pHandle); uint8_t MCPA_cfgLog(MCPA_Handle_t *pHandle, uint8_t *cfgdata); void MCPA_flushDataLog (MCPA_Handle_t *pHandle); #endif /* MCPA_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
3,856
C
42.337078
198
0.57028
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mcp.h
/** ****************************************************************************** * @file mcp.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides firmware functions that implement the Motor control protocol * 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 MOTOR_CONTROL_PROTOCOL_H #define MOTOR_CONTROL_PROTOCOL_H #include "mcptl.h" #define MCP_VERSION 0x1U /* Action suppoted by the Motor control protocol*/ #define CMD_MASK 0xFFF8U #define MCP_USER_CMD_MASK 0xFF00U #define GET_MCP_VERSION 0x0 #define SET_DATA_ELEMENT 0x8 #define GET_DATA_ELEMENT 0x10 #define START_MOTOR 0x18 #define STOP_MOTOR 0x20 #define STOP_RAMP 0x28 #define START_STOP 0x30 #define FAULT_ACK 0x38 #define CPULOAD_CLEAR 0x40 #define IQDREF_CLEAR 0x48 #define PFC_ENABLE 0x50 #define PFC_DISABLE 0x58 #define PFC_FAULT_ACK 0x60 #define PROFILER_CMD 0x68 #define SW_RESET 0x78 #define MCP_USER_CMD 0x100U /* MCP ERROR CODE */ #define MCP_CMD_OK 0x00U #define MCP_CMD_NOK 0x01U #define MCP_CMD_UNKNOWN 0x02U #define MCP_DATAID_UNKNOWN 0x03U #define MCP_ERROR_RO_REG 0x04U #define MCP_ERROR_UNKNOWN_REG 0x05U #define MCP_ERROR_STRING_FORMAT 0x06U #define MCP_ERROR_BAD_DATA_TYPE 0x07U #define MCP_ERROR_NO_TXSYNC_SPACE 0x08U #define MCP_ERROR_NO_TXASYNC_SPACE 0x09U #define MCP_ERROR_BAD_RAW_FORMAT 0x0AU #define MCP_ERROR_WO_REG 0x0BU #define MCP_ERROR_REGISTER_ACCESS 0x0CU #define MCP_ERROR_CALLBACK_NOT_REGISTRED 0x0DU #define MCP_HEADER_SIZE 2U /** @addtogroup MCSDK * @{ */ /** @addtogroup MCP * @{ */ /** * @brief MCP User call back function pointer structure * * @param rxLength : Length of the transmitted buffer * @param *rxBuffer : Buffer of data transmitted by the MCP controller device * @param txSyncFreeSpace : space available in txBuffer to send data back to the MCP controller * @param *txLength : Actual size of data that will be transmitted to the MCP controller must be < txSyncFreeSpace * @param *txBuffer : Data that will be transmitted to the MCP controller in response to the user command * * @retval MCP status */ typedef uint8_t (*MCP_user_cb_t)(uint16_t rxLength, uint8_t *rxBuffer, int16_t txSyncFreeSpace, uint16_t *txLength, uint8_t *txBuffer); /** * @brief Handle structure for MCP related components */ typedef struct { MCTL_Handle_t *pTransportLayer; /** Pointer to the MCTL structure */ uint8_t *rxBuffer; /** Buffer of data transmitted by the MCP controller device */ uint8_t *txBuffer; /** Data that will be transmitted to the MCP controller in response to the user command */ uint16_t rxLength; /** Length of the transmitted buffer */ uint16_t txLength; /** Actual size of data that will be transmitted to the MCP controller ; must be < txSyncFreeSpace*/ } MCP_Handle_t; /* Parses the received packet and call the required function depending on the command sent by the controller device. */ void MCP_ReceivedPacket(MCP_Handle_t *pHandle); /* Stores user's MCP functions to be acknowledged as MCP functions. */ uint8_t MCP_RegisterCallBack (uint8_t callBackID, MCP_user_cb_t fctCB); #endif /* MOTOR_CONTROL_PROTOCOL_H */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,558
C
36.368852
138
0.570864
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/esc.h
/** ****************************************************************************** * @file esc.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * esc 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 esc */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef ESC_H #define ESC_H #define ESC_FILTER_DEEP 4 #define ESC_BEEP_FEATURE typedef enum { ESC_ARMING = 0x00, ESC_ARMED = 0x01, ESC_POSITIVE_RUN = 0x02, ESC_STOP = 0x03, } ESC_sm_t; typedef enum { ESC_NOERROR = 0, ESC_NOSIGNAL = 1, ESC_PWM_BELOW_MIN = 2 } ESC_State_t; typedef enum { SM_BEEP_1 = 0x01, SM_BEEP_2 = 0x02, SM_BEEP_3 = 0x03, SM_BEEP_4 = 0x04, } ESC_Beep_State; typedef struct { TIM_TypeDef * Command_TIM; TIM_TypeDef * Motor_TIM; uint32_t ARMING_TIME; uint32_t PWM_TURNOFF_MAX; uint32_t TURNOFF_TIME_MAX; uint32_t Ton_max; uint32_t Ton_min; uint32_t Ton_arming; uint32_t delta_Ton_max; uint16_t speed_max_valueRPM; uint16_t speed_min_valueRPM; uint8_t motor; } ESC_Params_t; typedef struct { ESC_Params_t const * pESC_params; uint32_t pwm_buffer[ESC_FILTER_DEEP]; /*!< PWM filter variable */ uint32_t index_filter; uint32_t pwm_accumulator; uint32_t arming_counter; uint32_t pwm_timeout; int32_t turnoff_delay; volatile uint32_t Ton_value; int16_t restart_delay; #ifdef ESC_BEEP_FEATURE uint16_t beep_stop_time; uint16_t beep_counter; ESC_Beep_State beep_state; uint8_t beep_num; bool phase_check_status; bool start_check_flag; #endif ESC_sm_t sm_state; uint8_t watchdog_counter; uint8_t watchdog_counter_prev; bool buffer_completed; } ESC_Handle_t; void esc_boot(ESC_Handle_t * pHandle); void esc_pwm_stop(ESC_Handle_t * pHandle); ESC_State_t esc_pwm_run(ESC_Handle_t * pHandle); void esc_pwm_control(ESC_Handle_t * pHandle); #endif /*ESC_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,660
C
25.088235
84
0.584211
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/speed_pos_fdbk.h
/** ****************************************************************************** * @file speed_pos_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides all definitions and functions prototypes * of the 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 */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef SPEEDNPOSFDBK_H #define SPEEDNPOSFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ /* Already into mc_type.h */ /* #include "stdint.h" */ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief SpeednPosFdbk handles definitions of mechanical and electrical speed, mechanical acceleration, mechanical * and electrical angle and all constants and scale values for a reliable measure and * computation in appropriated unit. */ typedef struct { uint8_t bSpeedErrorNumber; /*!< Number of time the average mechanical speed is not valid. */ uint8_t bElToMecRatio; /*!< Coefficient used to transform electrical to mechanical quantities and viceversa. It usually coincides with motor pole pairs number. */ uint8_t SpeedUnit; /*!< The speed unit value is defined into mc_stm_types.h by [SPEED_UNIT](measurement_units.md) in tenth of Hertz.*/ uint8_t bMaximumSpeedErrorsNumber; /*!< Maximum value of not valid speed measurements before an error is reported.*/ int16_t hElAngle; /*!< Estimated electrical angle reported by the implemented speed and position method. */ int16_t hMecAngle; /*!< Instantaneous measure of rotor mechanical angle. */ int32_t wMecAngle; /*!< Mechanical angle frame based on coefficient #bElToMecRatio. */ int16_t hAvrMecSpeedUnit; /*!< Average mechanical speed expressed in the unit defined by [SPEED_UNIT](measurement_units.md). */ int16_t hElSpeedDpp; /*!< Instantaneous electrical speed expressed in Digit Per control Period ([dpp](measurement_units.md)), expresses the angular speed as the variation of the electrical angle. */ int16_t InstantaneousElSpeedDpp; /*!< Instantaneous computed electrical speed, expressed in [dpp](measurement_units.md). */ int16_t hMecAccelUnitP; /*!< Average mechanical acceleration expressed in the unit defined by #SpeedUnit, only reported with encoder implementation */ uint16_t hMaxReliableMecSpeedUnit; /*!< Maximum value of measured mechanical speed that is considered to be valid. Expressed in the unit defined by [SPEED_UNIT](measurement_units.md). */ uint16_t hMinReliableMecSpeedUnit; /*!< Minimum value of measured mechanical speed that is considered to be valid. Expressed in the unit defined by [SPEED_UNIT](measurement_units.md).*/ uint16_t hMaxReliableMecAccelUnitP; /*!< Maximum value of measured acceleration that is considered to be valid. Constant value equal to 65535, expressed in the unit defined by [SPEED_UNIT](measurement_units.md). */ uint16_t hMeasurementFrequency; /*!< Frequency at which the user will request a measurement of the rotor electrical angle. Expressed in PWM_FREQ_SCALING * Hz. */ uint32_t DPPConvFactor; /*!< Conversion factor (65536/#PWM_FREQ_SCALING) used to convert measured speed from the unit defined by [SPEED_UNIT](measurement_units.md) to [dpp](measurement_units.md). */ } SpeednPosFdbk_Handle_t; /** * @brief input structure type definition for SPD_CalcAngle */ typedef struct { alphabeta_t Valfa_beta; /*!< Voltage Components in alfa beta reference frame */ alphabeta_t Ialfa_beta; /*!< Current Components in alfa beta reference frame */ uint16_t Vbus; /*!< Virtual Bus Voltage information */ } Observer_Inputs_t; int16_t SPD_GetElAngle(const SpeednPosFdbk_Handle_t *pHandle); int32_t SPD_GetMecAngle(const SpeednPosFdbk_Handle_t *pHandle); int16_t SPD_GetAvrgMecSpeedUnit(const SpeednPosFdbk_Handle_t *pHandle); int16_t SPD_GetElSpeedDpp(const SpeednPosFdbk_Handle_t *pHandle); int16_t SPD_GetInstElSpeedDpp(const SpeednPosFdbk_Handle_t *pHandle); bool SPD_Check(const SpeednPosFdbk_Handle_t *pHandle); bool SPD_IsMecSpeedReliable(SpeednPosFdbk_Handle_t *pHandle, const int16_t *pMecSpeedUnit); int16_t SPD_GetS16Speed(const SpeednPosFdbk_Handle_t *pHandle); uint8_t SPD_GetElToMecRatio(const SpeednPosFdbk_Handle_t *pHandle); void SPD_SetElToMecRatio(SpeednPosFdbk_Handle_t *pHandle, uint8_t bPP); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* SPEEDNPOSFDBK_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
6,196
C
45.246268
119
0.57876
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/profiler_fluxestim.h
/** ****************************************************************************** * @file profiler_fluxestim.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * profiler flux estimator 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 * ****************************************************************************** * */ #ifndef _PROFILER_FLUXESTIM_H_ #define _PROFILER_FLUXESTIM_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "profiler_types.h" /** * @brief todo */ typedef enum _PROFILER_FLUXESTIM_State_e_ { PROFILER_FLUXESTIM_STATE_Idle, /*!< @brief todo */ PROFILER_FLUXESTIM_STATE_RampUpCur, /*!< @brief todo */ PROFILER_FLUXESTIM_STATE_RampUpFreq, /*!< @brief todo */ PROFILER_FLUXESTIM_STATE_FluxRefAuto, /*!< @brief todo */ PROFILER_FLUXESTIM_STATE_RampDownFreq, /*!< @brief todo */ PROFILER_FLUXESTIM_STATE_RampDownCur, /*!< @brief todo */ PROFILER_FLUXESTIM_STATE_Complete, /*!< @brief todo */ PROFILER_FLUXESTIM_STATE_Error, /*!< @brief todo */ } PROFILER_FLUXESTIM_State_e; /** * @brief todo */ typedef enum _PROFILER_FLUXESTIM_Error_e_ { PROFILER_FLUXESTIM_ERROR_None, /*!< @brief todo */ PROFILER_FLUXESTIM_ERROR_FluxNotValid, /*!< @brief todo */ } PROFILER_FLUXESTIM_Error_e; /** * @brief todo */ typedef struct _PROFILER_FLUXESTIM_Obj_ { PROFILER_FLUXESTIM_State_e state; /*!< @brief todo */ PROFILER_FLUXESTIM_Error_e error; /*!< @brief todo */ /* inputs */ /* outputs */ fixp30_t flux_Wb; /*!< @brief todo */ /* configuration */ bool glue_dcac_fluxestim_on; /*!< @brief todo */ uint32_t measurement_counts; /*!< @brief todo */ float_t measurement_time_s; /*!< @brief todo */ fixp30_t CurToRamp_sf_pu; /*!< @brief todo */ fixp30_t FreqToRamp_sf_pu; /*!< @brief todo */ fixp30_t Id_ref_pu; /*!< @brief todo */ fixp30_t FluxEstFreq_pu; /*!< @brief todo */ fixp30_t freqEst_pu; /*!< @brief todo */ fixp30_t freqHSO_pu; /*!< @brief todo */ fixp30_t ramp_rate_A_pu_per_cycle; /*!< @brief todo */ fixp30_t ramp_rate_freq_pu_per_cycle; /*!< @brief todo */ fixp30_t fluxEstimPoleTs; /*!< @brief todo */ float_t background_rate_hz; /*!< @brief todo */ float_t fullScaleCurrent_A; /*!< @brief todo */ float_t fullScaleVoltage_V; /*!< @brief todo */ float_t fullScaleFreq_Hz; /*!< @brief todo */ float_t voltagefilterpole_rps; /*!< @brief todo */ /* FluxEstim state data */ uint32_t counter; /*!< @brief todo */ } PROFILER_FLUXESTIM_Obj; /** * @brief todo */ typedef PROFILER_FLUXESTIM_Obj* PROFILER_FLUXESTIM_Handle; void PROFILER_FLUXESTIM_init(PROFILER_FLUXESTIM_Handle handle); void PROFILER_FLUXESTIM_setParams(PROFILER_FLUXESTIM_Handle handle, PROFILER_Params* pParams); void PROFILER_FLUXESTIM_run(PROFILER_FLUXESTIM_Handle handle, MOTOR_Handle motor); void PROFILER_FLUXESTIM_runBackground(PROFILER_FLUXESTIM_Handle handle, MOTOR_Handle motor); void PROFILER_FLUXESTIM_reset(PROFILER_FLUXESTIM_Handle handle, MOTOR_Handle motor); /* Accessors */ float_t PROFILER_FLUXESTIM_getFluxEstFreq_Hz(const PROFILER_FLUXESTIM_Handle handle); float_t PROFILER_FLUXESTIM_getMeasurementTime(PROFILER_FLUXESTIM_Handle handle); void PROFILER_FLUXESTIM_setFluxEstFreq_Hz(PROFILER_FLUXESTIM_Handle handle, const float_t fluxEstFreq_Hz); void PROFILER_FLUXESTIM_setMeasurementTime(PROFILER_FLUXESTIM_Handle handle, const float_t time_seconds); #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* _PROFILER_FLUXESTIM_H_ */ /* end of profiler_fluxestim.h */
4,544
C
35.071428
106
0.580106
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/digital_output.h
/** ****************************************************************************** * @file digital_output.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * digital output 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 DigitalOutput */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef DIGITALOUTPUT_H #define DIGITALOUTPUT_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup DigitalOutput * @{ */ /* Exported constants --------------------------------------------------------*/ #define DOutputActiveHigh 1U /*!< Digital output active high flag */ #define DOutputActiveLow 0U /*!< Digital output active low flag */ /* Exported types ------------------------------------------------------------*/ /** * @brief Digital output handler definition */ typedef struct { DOutputState_t OutputState; /*!< Indicates the state of the digital output. */ GPIO_TypeDef *hDOutputPort; /*!< GPIO output port. It must be equal to GPIOx x= A, B, ...*/ uint16_t hDOutputPin; /*!< GPIO output pin. It must be equal to GPIO_Pin_x x= 0, 1, ...*/ uint8_t bDOutputPolarity; /*!< GPIO output polarity. It must be equal to DOutputActiveHigh or DOutputActiveLow */ } DOUT_handle_t; /* Accordingly with selected polarity, it sets to active or inactive the * digital output */ void DOUT_SetOutputState(DOUT_handle_t *pHandle, DOutputState_t State); /* It returns the state of the digital output */ __weak DOutputState_t DOUT_GetOutputState(DOUT_handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* DIGITALOUTPUT_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,617
C
29.8
103
0.5235
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pqd_motor_power_measurement.h
/** ****************************************************************************** * @file pqd_motor_power_measurement.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * PQD Motor Power Measurement 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 pqd_motorpowermeasurement */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef PQD_MOTORPOWERMEASUREMENT_H #define PQD_MOTORPOWERMEASUREMENT_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "bus_voltage_sensor.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup pqd_motorpowermeasurement * @{ */ /** * @brief Handle of a PQD Motor Power Measurement component * * PQD Motor Power Measurement components compute a value of the average electrical power * flowing into a motor from the QD-frame @f$I_{qd}@f$ and @f$V_{qd}@f$ values. * */ typedef struct { int16_t hAvrgElMotorPower; /**< @brief Average measured motor power expressed in s16 digit (s16A x s16V). */ float_t ConvFact; /**< @brief Factor used to convert s16 digit average motor power values into Watts. Set to @f[\sqrt{3} \frac{V_{dd}}{R_{shunt} \times A_{op} \times 65536}@f]. */ pFOCVars_t pFOCVars; /**< @brief Pointer to FOC vars. */ BusVoltageSensor_Handle_t *pVBS; /**< @brief Bus voltage sensor component handle. */ } PQD_MotorPowMeas_Handle_t; /* Updates the average electrical motor power measure with the latest values of the DQ currents and voltages */ void PQD_CalcElMotorPower(PQD_MotorPowMeas_Handle_t *pHandle); /* Clears the the int16_t digit average motor power value stored in the handle */ void PQD_Clear(PQD_MotorPowMeas_Handle_t *pHandle); /* Returns an average value of the measured motor power expressed in Watts */ float_t PQD_GetAvrgElMotorPowerW(const PQD_MotorPowMeas_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* PQD_MOTORPOWERMEASUREMENT_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,844
C
32.470588
118
0.583333
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/gap_gate_driver_ctrl.h
/** ****************************************************************************** * @file gap_gate_driver_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * GAP component of the Motor Control SDK that provides support * the STGAPxx galvanically isolated gate drivers family. * ****************************************************************************** * @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 GAP_GATE_DRIVER_CTRL */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __GAP_GATE_DRIVER_CTR_H #define __GAP_GATE_DRIVER_CTR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup GAP_GATE_DRIVER_CTRL * @{ */ #define GPIO_NoRemap_SPI ((uint32_t)(0)) #define MAX_DEVICES_NUMBER 7 /**< @brief Number of GAP used in the project. */ #define CFG1_REG_MASK (uint8_t)(0xFF) /**< @brief Data mask for CFG1 register. */ #define CFG2_REG_MASK (uint8_t)(0xFF) /**< @brief Data mask for CFG2 register. */ #define CFG3_REG_MASK (uint8_t)(0xFF) /**< @brief Data mask for CFG3 register. */ #define CFG4_REG_MASK (uint8_t)(0x3F) /**< @brief Data mask for CFG4 register. */ #define CFG5_REG_MASK (uint8_t)(0x0F) /**< @brief Data mask for CFG5 register. */ #define STATUS1_REG_MASK (uint8_t)(0xFF) /**< @brief Data mask for STATUS1 register. */ #define STATUS2_REG_MASK (uint8_t)(0x06) /**< @brief Data mask for STATUS2 register. */ #define STATUS3_REG_MASK (uint8_t)(0x1F) /**< @brief Data mask for STATUS3 register. */ #define TEST1_REG_MASK (uint8_t)(0x1F) /**< @brief Data mask for TEST1 register. */ #define DIAG1_REG_MASK (uint8_t)(0xFF) /**< @brief Data mask for DIAG1 register. */ #define DIAG2_REG_MASK (uint8_t)(0xFF) /**< @brief Data mask for DIAG2 register. */ #define GAP_ERROR_CLEAR (uint32_t)(0x00000000) /**< @brief No ERROR occured. */ #define GAP_ERROR_CODE_UVLOD (uint32_t)(0x00000001) /**< @brief Under Voltage Lockout ERROR occured. */ #define GAP_ERROR_CODE_OVLOD (uint32_t)(0x00000002) /**< @brief Over Voltage Lockout ERROR occured. */ #define GAP_ERROR_CODE_REGERRL (uint32_t)(0x00000004) /**< @brief Configuration procedure occured. */ #define GAP_ERROR_CODE_SPI_ERR (uint32_t)(0x00000008) /**< @brief SPI communication ERROR occured. */ #define GAP_ERROR_CODE_DT_ERR (uint32_t)(0x00000010) /**< @brief Deadtime ERROR occured. */ #define GAP_ERROR_CODE_CFG (uint32_t)(0x00000020) /**< @brief Configuration ERROR occured. */ #define GAP_ERROR_CODE_GATE (uint32_t)(0x00000100) /**< @brief GATE path ERROR occured. */ #define GAP_ERROR_CODE_ASC (uint32_t)(0x00000200) /**< @brief Asynchronous stop command ERROR occured. */ #define GAP_ERROR_CODE_REGERRR (uint32_t)(0x00000400) /**< @brief Configuration procedure occured. */ #define GAP_ERROR_CODE_TWN (uint32_t)(0x00010000) /**< @brief Temperature warning threshold ERROR occured. */ #define GAP_ERROR_CODE_TSD (uint32_t)(0x00020000) /**< @brief Temperature threshold ERROR occured. */ #define GAP_ERROR_CODE_UVLOL (uint32_t)(0x00040000) /**< @brief Under Voltage Lockout on VL ERROR occured. */ #define GAP_ERROR_CODE_UVLOH (uint32_t)(0x00080000) /**< @brief Under Voltage Lockout on VH ERROR occured. */ #define GAP_ERROR_CODE_SENSE (uint32_t)(0x00100000) /**< @brief sensor SENS voltage ERROR occured. */ #define GAP_ERROR_CODE_DESAT (uint32_t)(0x00200000) /**< @brief sensor Desaturation protection ERROR occured. */ #define GAP_ERROR_CODE_OVLOL (uint32_t)(0x00400000) /**< @brief Over Voltage Lockout on VL ERROR occured. */ #define GAP_ERROR_CODE_OVLOH (uint32_t)(0x00800000) /**< @brief Over Voltage Lockout on VH ERROR occured. */ #define GAP_ERROR_CODE_SPI_CRC (uint32_t)(0x40000000) /**< @brief CRC SPI ERROR occured. */ #define GAP_ERROR_CODE_DEVICES_NOT_PROGRAMMABLE (uint32_t)(0x80000000) /**< @brief Device access ERROR occured. */ #define GAP_CFG1_CRC_SPI (uint8_t)(0x80) /**< @brief CFG1 register: SPI communication protocol CRC enable. */ #define GAP_CFG1_UVLOD (uint8_t)(0x40) /**< @brief CFG1 register: UVLO protection on VDD supply voltage enable. */ #define GAP_CFG1_SD_FLAG (uint8_t)(0x20) /**< @brief CFG1 register: SD pin functionality. */ #define GAP_CFG1_DIAG_EN (uint8_t)(0x10) /**< @brief CFG1 register: IN-/DIAG2 pin functionality. */ #define GAP_CFG1_DT_DISABLE (uint8_t)(0x00) /**< @brief CFG1 register: No deadtime value. */ #define GAP_CFG1_DT_250NS (uint8_t)(0x04) /**< @brief CFG1 register: 250ns deadtime value. */ #define GAP_CFG1_DT_800NS (uint8_t)(0x08) /**< @brief CFG1 register: 800ns deadtime value. */ #define GAP_CFG1_DT_1200NS (uint8_t)(0x0C) /**< @brief CFG1 register: 1200ns deadtime value. */ #define GAP_CFG1_INFILTER_DISABLE (uint8_t)(0x00) /**< @brief CFG1 register: No Input deglitch time value. */ #define GAP_CFG1_INFILTER_210NS (uint8_t)(0x01) /**< @brief CFG1 register: 210ns Input deglitch time value. */ #define GAP_CFG1_INFILTER_560NS (uint8_t)(0x02) /**< @brief CFG1 register: 560ns Input deglitch time value. */ #define GAP_CFG1_INFILTER_70NS (uint8_t)(0x03) /**< @brief CFG1 register: 70ns Input deglitch time value. */ #define GAP_CFG2_SENSETH_100MV (uint8_t)(0x00) /**< @brief CFG2 register: 100mV SENSE comparator threshold value. */ #define GAP_CFG2_SENSETH_125MV (uint8_t)(0x20) /**< @brief CFG2 register: 125mV SENSE comparator threshold value. */ #define GAP_CFG2_SENSETH_150MV (uint8_t)(0x40) /**< @brief CFG2 register: 150mV SENSE comparator threshold value. */ #define GAP_CFG2_SENSETH_175MV (uint8_t)(0x60) /**< @brief CFG2 register: 175mV SENSE comparator threshold value. */ #define GAP_CFG2_SENSETH_200MV (uint8_t)(0x80) /**< @brief CFG2 register: 200mV SENSE comparator threshold value. */ #define GAP_CFG2_SENSETH_250MV (uint8_t)(0xA0) /**< @brief CFG2 register: 250mV SENSE comparator threshold value. */ #define GAP_CFG2_SENSETH_300MV (uint8_t)(0xC0) /**< @brief CFG2 register: 300mV SENSE comparator threshold value. */ #define GAP_CFG2_SENSETH_400MV (uint8_t)(0xE0) /**< @brief CFG2 register: 400mV SENSE comparator threshold value. */ #define GAP_CFG2_DESATCURR_250UA (uint8_t)(0x00) /**< @brief CFG2 register: 250uA current value sourced by the DESAT. */ #define GAP_CFG2_DESATCURR_500UA (uint8_t)(0x08) /**< @brief CFG2 register: 500uA current value sourced by the DESAT. */ #define GAP_CFG2_DESATCURR_750UA (uint8_t)(0x10) /**< @brief CFG2 register: 750uA current value sourced by the DESAT. */ #define GAP_CFG2_DESATCURR_1000UA (uint8_t)(0x18) /**< @brief CFG2 register: 1000uA current value sourced by the DESAT. */ #define GAP_CFG2_DESATTH_3V (uint8_t)(0x00) /**< @brief CFG2 register: 3V DESAT comparator threshold value. */ #define GAP_CFG2_DESATTH_4V (uint8_t)(0x01) /**< @brief CFG2 register: 4V DESAT comparator threshold value. */ #define GAP_CFG2_DESATTH_5V (uint8_t)(0x02) /**< @brief CFG2 register: 5V DESAT comparator threshold value. */ #define GAP_CFG2_DESATTH_6V (uint8_t)(0x03) /**< @brief CFG2 register: 6V DESAT comparator threshold value. */ #define GAP_CFG2_DESATTH_7V (uint8_t)(0x04) /**< @brief CFG2 register: 7V DESAT comparator threshold value. */ #define GAP_CFG2_DESATTH_8V (uint8_t)(0x05) /**< @brief CFG2 register: 8V DESAT comparator threshold value. */ #define GAP_CFG2_DESATTH_9V (uint8_t)(0x06) /**< @brief CFG2 register: 9V DESAT comparator threshold value. */ #define GAP_CFG2_DESATTH_10V (uint8_t)(0x07) /**< @brief CFG2 register: 10V DESAT comparator threshold value. */ #define GAP_CFG3_2LTOTH_7_0V (uint8_t)(0x00) /**< @brief CFG3 register: 7V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_7_5V (uint8_t)(0x10) /**< @brief CFG3 register: 7.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_8_0V (uint8_t)(0x20) /**< @brief CFG3 register: 8V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_8_5V (uint8_t)(0x30) /**< @brief CFG3 register: 8.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_9_0V (uint8_t)(0x40) /**< @brief CFG3 register: 9V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_9_5V (uint8_t)(0x50) /**< @brief CFG3 register: 9.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_10_0V (uint8_t)(0x60) /**< @brief CFG3 register: 10V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_10_5V (uint8_t)(0x70) /**< @brief CFG3 register: 10.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_11_0V (uint8_t)(0x80) /**< @brief CFG3 register: 11V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_11_5V (uint8_t)(0x90) /**< @brief CFG3 register: 11.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_12_0V (uint8_t)(0xA0) /**< @brief CFG3 register: 12V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_12_5V (uint8_t)(0xB0) /**< @brief CFG3 register: 12.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_13_0V (uint8_t)(0xC0) /**< @brief CFG3 register: 13V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_13_5V (uint8_t)(0xD0) /**< @brief CFG3 register: 13.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_14_0V (uint8_t)(0xE0) /**< @brief CFG3 register: 14V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTH_14_5V (uint8_t)(0xF0) /**< @brief CFG3 register: 14.5V threshold voltage value which is actively forced during the 2-level turnoff sequence. */ #define GAP_CFG3_2LTOTIME_DISABLE (uint8_t)(0x00) /**< @brief CFG3 register: No duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_0_75_US (uint8_t)(0x01) /**< @brief CFG3 register: 0.75us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_1_00_US (uint8_t)(0x02) /**< @brief CFG3 register: 1us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_1_50_US (uint8_t)(0x03) /**< @brief CFG3 register: 1.5us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_2_00_US (uint8_t)(0x04) /**< @brief CFG3 register: 2us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_2_50_US (uint8_t)(0x05) /**< @brief CFG3 register: 2.5us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_3_00_US (uint8_t)(0x06) /**< @brief CFG3 register: 3us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_3_50_US (uint8_t)(0x07) /**< @brief CFG3 register: 3.5us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_3_75_US (uint8_t)(0x08) /**< @brief CFG3 register: 3.75us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_4_00_US (uint8_t)(0x09) /**< @brief CFG3 register: 4us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_4_25_US (uint8_t)(0x0A) /**< @brief CFG3 register: 4.25us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_4_50_US (uint8_t)(0x0B) /**< @brief CFG3 register: 4.5us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_4_75_US (uint8_t)(0x0C) /**< @brief CFG3 register: 4.75us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_5_00_US (uint8_t)(0x0D) /**< @brief CFG3 register: 5us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_5_25_US (uint8_t)(0x0E) /**< @brief CFG3 register: 5.25us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG3_2LTOTIME_5_50_US (uint8_t)(0x0F) /**< @brief CFG3 register: 5.5us duration time value of the 2-level turn-off sequence. */ #define GAP_CFG4_OVLO (uint8_t)(0x20) /**< @brief CFG4 register: enables the OVLO protection on the VH and VL power supply. */ #define GAP_CFG4_UVLOLATCH (uint8_t)(0x10) /**< @brief CFG4 register: sets if the UVLO is latched or not. */ #define GAP_CFG4_UVLOTH_VH_DISABLE (uint8_t)(0x00) /**< @brief CFG4 register: disables the UVLO threshold on the positive power supply. */ #define GAP_CFG4_UVLOTH_VH_10V (uint8_t)(0x01) /**< @brief CFG4 register: sets the VH positive supply voltage UVLO threshold to 10v on the positive power supply. */ #define GAP_CFG4_UVLOTH_VH_12V (uint8_t)(0x02) /**< @brief CFG4 register: sets the VH positive supply voltage UVLO threshold to 12v on the positive power supply. */ #define GAP_CFG4_UVLOTH_VH_14V (uint8_t)(0x03) /**< @brief CFG4 register: sets the VH positive supply voltage UVLO threshold to 140v on the positive power supply. */ #define GAP_CFG4_UVLOTH_VL_DISABLE (uint8_t)(0x00) /**< @brief CFG4 register: disables the UVLO threshold on the negative power supply. */ #define GAP_CFG4_UVLOTH_VL_N3V (uint8_t)(0x04) /**< @brief CFG4 register: sets the VL negative supply voltage UVLO threshold to -3v on the negative power supply. */ #define GAP_CFG4_UVLOTH_VL_N5V (uint8_t)(0x08) /**< @brief CFG4 register: sets the VL negative supply voltage UVLO threshold to -5v on the negative power supply. */ #define GAP_CFG4_UVLOTH_VL_N7V (uint8_t)(0x0C) /**< @brief CFG4 register: sets the VL negative supply voltage UVLO threshold to -7v on the negative power supply. */ #define GAP_CFG5_2LTO_ON_FAULT (uint8_t)(0x08) /**< @brief CFG5 register: 2LTO active only after a fault event. */ #define GAP_CFG5_CLAMP_EN (uint8_t)(0x04) /**< @brief CFG5 register: enables enable the Miller clamp feature. */ #define GAP_CFG5_DESAT_EN (uint8_t)(0x02) /**< @brief CFG5 register: enables the DESAT desaturation protection function comparator. */ #define GAP_CFG5_SENSE_EN (uint8_t)(0x01) /**< @brief CFG5 register: enables the sense overcurrent function comparator. */ #define GAP_STATUS1_OVLOH (uint8_t)(0x80) /**< @brief STATUS1 register: VH overvoltage flag is forced high when VH is over OVVHoff threshold. */ #define GAP_STATUS1_OVLOL (uint8_t)(0x40) /**< @brief STATUS1 register: VL overvoltage flag is forced high when VL is over OVVLoff threshold. */ #define GAP_STATUS1_DESAT (uint8_t)(0x20) /**< @brief STATUS1 register: Desaturation flag is forced high when DESAT pin voltage reach VDESATth threshold. */ #define GAP_STATUS1_SENSE (uint8_t)(0x10) /**< @brief STATUS1 register: Sense flag is forced high when SENSE pin voltage reach VSENSEth threshold. */ #define GAP_STATUS1_UVLOH (uint8_t)(0x08) /**< @brief STATUS1 register: VH undervoltage flag is forced high when VH is below VHoff threshold. */ #define GAP_STATUS1_UVLOL (uint8_t)(0x04) /**< @brief STATUS1 register: VL undervoltage flag is forced high when VL is over VLoff threshold. */ #define GAP_STATUS1_TSD (uint8_t)(0x02) /**< @brief STATUS1 register: Thermal shutdown protection flag is forced high when overtemperature shutdown threshold is reached.*/ #define GAP_STATUS1_TWN (uint8_t)(0x01) /**< @brief STATUS1 register: Thermal warning flag is forced high when overtemperature shutdown threshold is reached. */ #define GAP_STATUS2_REGERRR (uint8_t)(0x02) /**< @brief STATUS2 register: Register or communication error on isolated side is forced high when: 1 Programming procedure is not correctly performed. 2 Isolated interface communication fails. 3 An unexpected register value change occurs in one of the remote registers. It is also latched at power-up/reset and from Sleep state. */ #define GAP_STATUS2_ASC (uint8_t)(0x01) /**< @brief STATUS2 register: ASC pin status. When ASC pin is high the flag reports '1', otherwise is '0'.. */ #define GAP_STATUS3_CFG (uint8_t)(0x20) /**< @brief STATUS3 register: CFG error flag. */ #define GAP_STATUS3_DT_ERR (uint8_t)(0x10) /**< @brief STATUS3 register: Deadtime error flag is forced high when a violation of internal DT is detected. */ #define GAP_STATUS3_SPI_ERR (uint8_t)(0x08) /**< @brief STATUS3 register: SPI communication error flag is forced high when the SPI communication fails cause: 1 Wrong CRC check. 2 Wrong number of CK rising edges. 3 Attempt to execute a not-allowed command. 4 Attempt to read, write or reset at a not available address. */ #define GAP_STATUS3_REGERRL (uint8_t)(0x04) /**< @brief STATUS3 register: Register or communication error on low voltage side is forced high when: - 1 Programming procedure is not correctly performed. 2 Isolated interface communication fails. 3 An unexpected register value change occurs in one of the remote registers. * It is latched at power-up/reset also. */ #define GAP_STATUS3_OVLOD (uint8_t)(0x02) /**< @brief STATUS3 register: VDD overvoltage flag is forced high when VDD is over OVVDDoff threshold. */ #define GAP_STATUS3_UVLOD (uint8_t)(0x01) /**< @brief STATUS3 register: VDD undervoltage flag is forced high when VDD is below VDDon threshold. It is latched at power-up/reset also. */ #define GAP_TEST1_GOFFCHK (uint8_t)(0x10) /**< @brief TEST1 register: enables the GOFF to gate path check mode */ #define GAP_TEST1_GONCHK (uint8_t)(0x08) /**< @brief TEST1 register: enables the GON to gate path check mode */ #define GAP_TEST1_DESCHK (uint8_t)(0x04) /**< @brief TEST1 register: enables the DESAT comparator check mode */ #define GAP_TEST1_SNSCHK (uint8_t)(0x02) /**< @brief TEST1 register: enables the SENSE comparator check mode */ #define GAP_TEST1_RCHK (uint8_t)(0x01) /**< @brief TEST1 register: enables the SENSE resistor check mode */ #define GAP_DIAG_SPI_REGERR (uint8_t)(0x80) /**< @brief DIAG register: enables the DIAGxCFG event SPI communication error or register failure */ #define GAP_DIAG_UVLOD_OVLOD (uint8_t)(0x40) /**< @brief DIAG register: enables the DIAGxCFG event VDD power supply failure */ #define GAP_DIAG_UVLOH_UVLOL (uint8_t)(0x20) /**< @brief DIAG register: enables the DIAGxCFG event Undervoltage failure */ #define GAP_DIAG_OVLOH_OVLOL (uint8_t)(0x10) /**< @brief DIAG register: enables the DIAGxCFG event Overvoltage failure */ #define GAP_DIAG_DESAT_SENSE (uint8_t)(0x08) /**< @brief DIAG register: enables the DIAGxCFG event SDesaturation and sense detection */ #define GAP_DIAG_ASC_DT_ERR (uint8_t)(0x04) /**< @brief DIAG register: enables the DIAGxCFG event ASC feedback */ #define GAP_DIAG_TSD (uint8_t)(0x02) /**< @brief DIAG register: enables the DIAGxCFG event Thermal shutdown */ #define GAP_DIAG_TWN (uint8_t)(0x01) /**< @brief DIAG register: enables the DIAGxCFG event Thermal warning */ #define GAP_DIAG_NONE (uint8_t)(0x00) /**< @brief DIAG register: No DIAGxCFG event. */ /** Define the GAP register enum. * */ typedef enum { CFG1 = 0x0C, /*!< Address of CFG1 register (low voltage side). */ CFG2 = 0x1D, /*!< Address of CFG2 register (isolated side). */ CFG3 = 0x1E, /*!< Address of CFG3 register (isolated side). */ CFG4 = 0x1F, /*!< Address of CFG4 register (isolated side). */ CFG5 = 0x19, /*!< Address of CFG5 register (isolated side). */ STATUS1 = 0x02, /*!< Address of STATUS1 register (low voltage side). The STATUS1 is a read only register that reports some device failure flags. */ STATUS2 = 0x01, /*!< Address of STATUS2 register (low voltage side). */ STATUS3 = 0x0A, /*!< Address of STATUS3 register (low voltage side). */ TEST1 = 0x11, /*!< Address of TEST1 register (isolated side). */ DIAG1 = 0x05, /*!< Address of DIAG1CFG registers (low voltage side). */ DIAG2 = 0x06 /*!< Address of DIAG2CFG registers (low voltage side). */ } GAP_Registers_Handle_t; /** Define test modes * */ typedef enum { SENSE_RESISTOR_CHK, /*!< Security check to verify the connection between the device and the sense shunt resistor and to verify the optional sense resistor filter network is not open. */ SENSE_COMPARATOR_CHK, /*!< Security check to verify the functionality of the sense comparator. */ GON_CHK, /*!< Security check to verify the path integrity including the driver's GON output, the GON (turn-on) gate resistor, the power switch gate and the CLAMP pin. */ GOFF_CHK, /*!< Security check to verify the path integrity including the driver's GOFF output, the GOFF (turn-off) gate resistor, the power switch gate and the CLAMP pin. */ DESAT_CHK /*!< Security check to verify the functionality of the de-saturation. */ } GAP_TestMode_t; /** * @brief GAP class register bank definition * * This structure contains configuration value for register bank of the GAP driver. * */ typedef struct { uint8_t CFG1; /*!< Configuration value for CFG1 register. */ uint8_t CFG2; /*!< Configuration value for CFG2 register. */ uint8_t CFG3; /*!< Configuration value for CFG3 register. */ uint8_t CFG4; /*!< Configuration value for CFG4 register. */ uint8_t CFG5; /*!< Configuration value for CFG5 register. */ uint8_t DIAG1; /*!< Configuration value for DIAG1 register. */ uint8_t DIAG2; /*!< Configuration value for DIAG2 register. */ } GAP_DeviceParams_Handle_t; /** * @brief Handle of the GAP component * * This structure holds all the parameters needed to access and manage GAP drivers. */ typedef struct { uint8_t DeviceNum; /*!< Number of GAP used in the daisy chain. */ GAP_DeviceParams_Handle_t DeviceParams[MAX_DEVICES_NUMBER]; /*!< Device parameters pointers */ /* SPI related parameters. */ SPI_TypeDef *SPIx; GPIO_TypeDef *NCSPort; /*!< GPIO port used by NCS. It must be equal to GPIOx x= A, B, ...*/ uint16_t NCSPin; /*!< GPIO pin used by NCS. It must be equal to GPIO_Pin_x x= 0, 1, ...*/ GPIO_TypeDef *NSDPort; /*!< GPIO port used by NSD. It must be equal to GPIOx x= A, B, ...*/ uint16_t NSDPin; /*!< GPIO pin used by NSD. It must be equal to GPIO_Pin_x x= 0, 1, ...*/ uint32_t GAP_ErrorsNow[MAX_DEVICES_NUMBER]; /*!< Bitfield with extra error codes that is currently active. The error code available are listed here (TBF).*/ uint32_t GAP_ErrorsOccurred[MAX_DEVICES_NUMBER]; /*!< Bitfield with extra error codes that occurs and is over. The error code available are listed here (TBF).*/ } GAP_Handle_t; /* Exported functions ------------------------------------------------------- */ bool GAP_CheckErrors(GAP_Handle_t *pHandle, uint32_t *error_now, uint32_t *error_occurred); void GAP_FaultAck(GAP_Handle_t *pHandle); bool GAP_Configuration(GAP_Handle_t *pHandle); bool GAP_IsDevicesProgrammed(GAP_Handle_t *pHandle); bool GAP_DevicesConfiguration(GAP_Handle_t *pHandle); uint16_t GAP_CRCCalculate(uint8_t data, uint8_t crc_initial_value); bool GAP_CRCCheck(uint8_t *out, uint16_t data_in); void wait(uint16_t count); uint8_t GAP_RegMask(GAP_Registers_Handle_t reg); bool GAP_ReadRegs(GAP_Handle_t *pHandle, uint8_t *pDataRead, GAP_Registers_Handle_t reg); void GAP_StartConfig(GAP_Handle_t *pHandle); void GAP_StopConfig(GAP_Handle_t *pHandle); bool GAP_WriteRegs(GAP_Handle_t *pHandle, uint8_t *pDataWrite, GAP_Registers_Handle_t reg); void GAP_GlobalReset(GAP_Handle_t *pHandle); bool GAP_ResetStatus(GAP_Handle_t *pHandle, GAP_Registers_Handle_t reg); bool GAP_Test(GAP_Handle_t *pHandle, GAP_TestMode_t testMode); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* __GAP_GATE_DRIVER_CTR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
29,376
C
91.380503
199
0.585103
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/r_divider_bus_voltage_sensor.h
/** ****************************************************************************** * @file r_divider_bus_voltage_sensor.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Resistor Divider Bus Voltage Sensor 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 RDividerBusVoltageSensor */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef RDIVIDER_BUSVOLTAGESENSOR_H #define RDIVIDER_BUSVOLTAGESENSOR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "regular_conversion_manager.h" #include "bus_voltage_sensor.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup BusVoltageSensor * @{ */ /** @addtogroup RDividerBusVoltageSensor * @{ */ /** * @brief Rdivider class parameters definition */ typedef struct { BusVoltageSensor_Handle_t _Super; /*!< Bus voltage sensor component handle. */ uint16_t LowPassFilterBW; /*!< Use this number to configure the Vbus first order software filter bandwidth. hLowPassFilterBW = VBS_CalcBusReading call rate [Hz]/ FilterBandwidth[Hz] */ uint16_t OverVoltageThreshold; /*!< It represents the over voltage protection intervention threshold. To be expressed in digital value through formula: hOverVoltageThreshold (digital value) = Over Voltage Threshold (V) * 65536 / hConversionFactor */ uint16_t OverVoltageThresholdLow; /*!< It represents the over voltage protection intervention threshold low level for hysteresis feature when "switch on brake resistor" is used. To be expressed in digital value through formula: hOverVoltageThresholdLow (digital value) = Over Voltage Threshold Low(V) * 65536 / hConversionFactor */ bool OverVoltageHysteresisUpDir; /*!< "Switch on brake resistor" hysteresis direction. */ uint16_t UnderVoltageThreshold; /*!< It represents the under voltage protection intervention threshold. To be expressed in digital value through formula: hUnderVoltageThreshold (digital value)= Under Voltage Threshold (V) * 65536 / hConversionFactor */ 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 to the regular conversion */ } RDivider_Handle_t; /* Exported functions ------------------------------------------------------- */ void RVBS_Init(RDivider_Handle_t *pHandle); void RVBS_Clear(RDivider_Handle_t *pHandle); uint16_t RVBS_CalcAvVbusFilt(RDivider_Handle_t *pHandle); uint16_t RVBS_CalcAvVbus(RDivider_Handle_t *pHandle, uint16_t rawValue); uint16_t RVBS_CheckFaultState(RDivider_Handle_t *pHandle); /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* RDIVIDER_BUSVOLTAGESENSOR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,733
C
42.431192
103
0.484893
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/profiler_handle.h
/** ****************************************************************************** * @file profiler_handle.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_handle.h */ #ifndef _PROFILER_HANDLE_H_ #define _PROFILER_HANDLE_H_ typedef struct _PROFILER_Obj_* PROFILER_Handle; #endif /* _PROFILER_HANDLE_H_ */ /* end of profiler_handle.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
1,075
C
33.709676
94
0.488372
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mp_hall_tuning.h
/** ****************************************************************************** * @file mp_hall_tuning.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for * for the Hall effect position sensors 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 * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MP_HALL_TUNING_H #define __MP_HALL_TUNING_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 "hall_speed_pos_fdbk.h" #include "pmsm_motor_parameters.h" #include "ramp_ext_mngr.h" #include "mc_math.h" #include "mc_interface.h" /* Hall Sensors Pins Def------------------------------------------------------*/ #define NO_COMPLEMENT 0x0 #define H1 0x1 #define H2 0x2 #define H3 0x4 #define HALL_FLAG_TIMEOUT 1000 #define WAIT_RAMP_TIMEOUT 10000 /** @addtogroup STM32_PMSM_MC_Library * @{ */ /** @addtogroup SelfComCtrl * @{ */ /** @defgroup SelfComCtrl_class_private_types SelfComCtrl class private types * @{ */ /** * @brief HT_State_t enum type definition, it lists all the possible HT machine states. */ typedef enum { HT_IDLE, /* 0 */ HT_PRIOR_CHECK, /* 1 */ HT_START_RAMP, /* 2 */ HT_WAIT_RAMP, /* 3 */ HT_WAIT_HALL_FLAG, /* 4 */ HT_CHECK_HALL_RELIABILITY, /* 5 */ HT_WAIT_USER_DIRECTION_CHOICE, /* 6 */ HT_ERROR_RELIABILITY, /* 7 */ HT_ERROR_PINS_READING, /* 8 */ HT_WARNING_PHASES_NEED_SWAP, /* 9 */ HT_DETECTING_CONF, /* 10 */ HT_DETERMINE_PTC, /* 11 */ HT_DETECTING_SWAP, /* 12 */ HT_WAIT_STABILIZATION, /* 13 */ HT_DETECTING_EDGE, HT_GET_ANGLE_EDGE, HT_CALC_EDGE_ANGLE, HT_EDGE_COMPUTATION, HT_RST, /* 16 */ HT_RESULT /* 17 */ } HT_State_t; /** * @brief HT_State_t enum type definition, it lists all the possible HT_SHIF_EDGE machine states. */ typedef enum { SHIFT_EDGE_IDLE, /* 0 */ SHIFT_EDGE_1, /* 1 */ SHIFT_EDGE_2, /* 2 */ SHIFT_EDGE_3, /* 3 */ SHIFT_EDGE_4, /* 4 */ SHIFT_EDGE_5, /* 5 */ SHIFT_EDGE_6, /* 6 */ SHIFT_EDGE_END /* 7 */ } ShiftEdge_State_t; /** * * @brief Handle structure of the HallTuning. */ typedef struct { MCI_Handle_t *pMCI; /*!< State machine of related MC.*/ OTT_Handle_t *pOTT; HALL_Handle_t *pHALL_M1; STO_PLL_Handle_t *pSTO_PLL_M1; HT_State_t sm_state; /*!< HT state machine state.*/ bool HT_Start; bool directionAlreadyChosen; bool userWantsToRestart; bool userWantsToAbort; bool flagState0; /*!< true if current HALL state configuration is H1=H2=H3=0. Used to detect 60 degrees Hall configuration */ bool flagState1; /*!< true if current HALL state configuration H1=H2=H3=1. Used to detect 60 degrees Hall configuration */ bool H1Connected; bool H2Connected; bool H3Connected; bool PTCWellPositioned; bool waitHallFlagCompleted; bool reliable; bool edgeAngleDirPos; uint8_t bPlacement; uint8_t bMechanicalWantedDirection; uint8_t bNewH1; uint8_t bNewH2; uint8_t bNewH3; uint8_t bProgressPercentage; int8_t bPinToComplement; uint16_t hHallFlagCnt; uint16_t hWaitRampCnt; uint16_t hShiftAngleDepth; int16_t hPhaseShiftInstantaneous; int16_t hPhaseShiftCircularMean; int16_t hPhaseShiftCircularMeanDeg; int16_t hPhaseShiftCircularMeanNeg; int16_t hPhaseShiftCircularMeanNegDeg; uint32_t previousH1; uint32_t previousH2; uint32_t previousH3; int32_t wSinMean; int32_t wCosMean; ShiftEdge_State_t shiftEdge_state; int32_t wSinSum1; int32_t wCosSum1; int32_t wSinSum2; int32_t wCosSum2; int32_t wSinSum3; int32_t wCosSum3; int32_t wSinSum4; int32_t wCosSum4; int32_t wSinSum5; int32_t wCosSum5; int32_t wSinSum6; int32_t wCosSum6; int16_t hPhaseShiftCircularMean5_1; int16_t hPhaseShiftCircularMeanDeg5_1; int16_t hPhaseShiftCircularMean1_3; int16_t hPhaseShiftCircularMeanDeg1_3; int16_t hPhaseShiftCircularMean3_2; int16_t hPhaseShiftCircularMeanDeg3_2; int16_t hPhaseShiftCircularMean2_6; int16_t hPhaseShiftCircularMeanDeg2_6; int16_t hPhaseShiftCircularMean6_4; int16_t hPhaseShiftCircularMeanDeg6_4; int16_t hPhaseShiftCircularMean4_5; int16_t hPhaseShiftCircularMeanDeg4_5; int16_t hPhaseShiftCircularMean5_4; int16_t hPhaseShiftCircularMeanDeg5_4; int16_t hPhaseShiftCircularMean4_6; int16_t hPhaseShiftCircularMeanDeg4_6; int16_t hPhaseShiftCircularMean6_2; int16_t hPhaseShiftCircularMeanDeg6_2; int16_t hPhaseShiftCircularMean2_3; int16_t hPhaseShiftCircularMeanDeg2_3; int16_t hPhaseShiftCircularMean3_1; int16_t hPhaseShiftCircularMeanDeg3_1; int16_t hPhaseShiftCircularMean1_5; int16_t hPhaseShiftCircularMeanDeg1_5; } HT_Handle_t; void HT_Init( HT_Handle_t * pHandleHT, bool pRST ); void HT_MF( HT_Handle_t * pHandleHT ); void HT_GetPhaseShift( HT_Handle_t * pHandleHT ); void HT_Stop( HT_Handle_t * pHandleHT ); void HT_SetMechanicalWantedDirection( HT_Handle_t * pHandleHT, uint8_t bMWD ); void HT_SetStart ( HT_Handle_t * pHandleHT, bool value ); void HT_SetRestart ( HT_Handle_t * pHandleHT ); void HT_SetAbort( HT_Handle_t * pHandleHT ); /** * @} */ /** * @} */ /** * @} */ #endif /*__MP_HALL_TUNING_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
6,491
C
26.74359
127
0.62733
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/fixpmpyxufloat.h
/** ****************************************************************************** * @file fixpmpyxufloat.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 * ****************************************************************************** */ /* fixpmpyxufloat.h */ #ifndef _FIXPMPYXUFLOAT_H_ #define _FIXPMPYXUFLOAT_H_ /* Multiply a variable of _any_ FIXP format with a floating point number * This is used for compile-time constant float values only */ #define FIXPmpy_xuFloat(var,fixed_float) \ (((fixed_float) < 1.0) ? (FIXP30_rsmpy((var),FIXP30(fixed_float)))\ :(((fixed_float) < 2.0) ? (FIXP29_rsmpy((var),FIXP29(fixed_float)))\ :(((fixed_float) < 4.0) ? (FIXP28_rsmpy((var),FIXP28(fixed_float)))\ :(((fixed_float) < 8.0) ? (FIXP27_rsmpy((var),FIXP27(fixed_float)))\ :(((fixed_float) < 16.0) ? (FIXP26_rsmpy((var),FIXP26(fixed_float)))\ :(((fixed_float) < 32.0) ? (FIXP25_rsmpy((var),FIXP25(fixed_float)))\ :(((fixed_float) < 64.0) ? (FIXP24_rsmpy((var),FIXP24(fixed_float)))\ :(((fixed_float) < 128.0) ? (FIXP23_rsmpy((var),FIXP23(fixed_float)))\ :(((fixed_float) < 256.0) ? (FIXP22_rsmpy((var),FIXP22(fixed_float)))\ :(((fixed_float) < 512.0) ? (FIXP21_rsmpy((var),FIXP21(fixed_float)))\ :(((fixed_float) < 1024.0) ? (FIXP20_rsmpy((var),FIXP20(fixed_float)))\ :(((fixed_float) < 2048.0) ? (FIXP19_rsmpy((var),FIXP19(fixed_float)))\ :(((fixed_float) < 4096.0) ? (FIXP18_rsmpy((var),FIXP18(fixed_float)))\ :(((fixed_float) < 8192.0) ? (FIXP17_rsmpy((var),FIXP17(fixed_float)))\ :(((fixed_float) < 16384.0) ? (FIXP16_rsmpy((var),FIXP16(fixed_float)))\ :(((fixed_float) < 32768.0) ? (FIXP15_rsmpy((var),FIXP15(fixed_float)))\ :(((fixed_float) < 65536.0) ? (FIXP14_rsmpy((var),FIXP14(fixed_float)))\ :(((fixed_float) < 131072.0) ? (FIXP13_rsmpy((var),FIXP13(fixed_float)))\ :(((fixed_float) < 262144.0) ? (FIXP12_rsmpy((var),FIXP12(fixed_float)))\ :(((fixed_float) < 524288.0) ? (FIXP11_rsmpy((var),FIXP11(fixed_float)))\ :(((fixed_float) < 1048567.0) ? (FIXP10_rsmpy((var),FIXP10(fixed_float)))\ :(((fixed_float) < 2097152.0) ? ( FIXP9_rsmpy((var),FIXP9(fixed_float))) \ :(((fixed_float) < 4194304.0) ? ( FIXP8_rsmpy((var),FIXP8(fixed_float))) \ :(((fixed_float) < 8388608.0) ? ( FIXP7_rsmpy((var),FIXP7(fixed_float))) \ :(((fixed_float) < 16777216.0) ? ( FIXP6_rsmpy((var),FIXP6(fixed_float))) \ :(((fixed_float) < 33554432.0) ? ( FIXP5_rsmpy((var),FIXP5(fixed_float))) \ :(((fixed_float) < 67108864.0) ? ( FIXP4_rsmpy((var),FIXP4(fixed_float))) \ :(((fixed_float) < 134217728.0) ? ( FIXP3_rsmpy((var),FIXP3(fixed_float))) \ :(((fixed_float) < 268435456.0) ? ( FIXP2_rsmpy((var), FIXP2(fixed_float)))\ : ( FIXP1_mpy((var), FIXP1(fixed_float)))))))))))))))))))))))))))))))) #endif /* _FIXPMPYXUFLOAT_H_ */ /* end of fixpmpyxufloat.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
3,779
C
58.062499
112
0.518656
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/feed_forward_ctrl.h
/** ****************************************************************************** * @file feed_forward_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Feed Forward 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 FeedForwardCtrl */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef FEEDFORWARDCTRL_H #define FEEDFORWARDCTRL_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "bus_voltage_sensor.h" #include "speed_pos_fdbk.h" #include "speed_torq_ctrl.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup FeedForwardCtrl * @{ */ /** * @brief Handle structure of the Feed-forward Component */ typedef struct { qd_t Vqdff; /**< Feed Forward controller @f$I_{qd}@f$ contribution to @f$V_{qd}@f$ */ qd_t VqdPIout; /**< @f$V_{qd}@f$ as output by PID controller */ qd_t VqdAvPIout; /**< Averaged @f$V_{qd}@f$ as output by PID controller */ int32_t wConstant_1D; /**< Feed forward default constant for the @f$d@f$ axis */ int32_t wConstant_1Q; /**< Feed forward default constant for the @f$q@f$ axis */ int32_t wConstant_2; /**< Default constant value used by Feed-forward algorithm */ BusVoltageSensor_Handle_t *pBus_Sensor; /**< Related bus voltage sensor */ PID_Handle_t *pPID_q; /*!< Related PI for @f$I_{q}@f$ regulator */ PID_Handle_t *pPID_d; /*!< Related PI for @f$I_{d}@f$ regulator */ uint16_t hVqdLowPassFilterBW; /**< Use this parameter to configure the Vqd first order software filter bandwidth. In case FULL_MISRA_COMPLIANCY, hVqdLowPassFilterBW is used and equal to FOC_CurrController call rate [Hz]/ FilterBandwidth[Hz]. On the contrary, if FULL_MISRA_COMPLIANCY is not defined, hVqdLowPassFilterBWLOG is used and equal to log with base two of previous definition */ int32_t wDefConstant_1D; /**< Feed forward default constant for d axes */ int32_t wDefConstant_1Q; /**< Feed forward default constant for q axes */ int32_t wDefConstant_2; /**< Default constant value used by Feed-forward algorithm*/ uint16_t hVqdLowPassFilterBWLOG; /**< hVqdLowPassFilterBW expressed as power of 2. E.g. if gain divisor is 512 the value must be 9 because 2^9 = 512 */ } FF_Handle_t; /* * Initializes all the component variables */ void FF_Init(FF_Handle_t *pHandle, BusVoltageSensor_Handle_t *pBusSensor, PID_Handle_t *pPIDId, PID_Handle_t *pPIDIq); /* * It should be called before each motor restart and clears the Feed-forward * internal variables. */ void FF_Clear(FF_Handle_t *pHandle); /* * It implements Feed-forward controller by computing new Vqdff value. * This will be then summed up to PI output in FF_VqdConditioning * method. */ void FF_VqdffComputation(FF_Handle_t *pHandle, qd_t Iqdref, SpeednTorqCtrl_Handle_t *pSTC); /* * It returns the Vqd components computed by input plus the Feed-forward * action and store the last Vqd values in the internal variable. */ qd_t FF_VqdConditioning(FF_Handle_t *pHandle, qd_t Vqd); /* * It low-pass filters the Vqd voltage coming from the speed PI. Filter * bandwidth depends on hVqdLowPassFilterBW parameter. */ void FF_DataProcess(FF_Handle_t *pHandle); /* * Use this method to initialize FF variables in START_TO_RUN state. */ void FF_InitFOCAdditionalMethods(FF_Handle_t *pHandle); /* * Use this method to set new constants values used by * Feed-forward algorithm. */ void FF_SetFFConstants(FF_Handle_t *pHandle, FF_TuningStruct_t sNewConstants); /* * Use this method to get present constants values used by * Feed-forward algorithm. */ FF_TuningStruct_t FF_GetFFConstants(FF_Handle_t *pHandle); /* * Use this method to get present values for the Vqd Feed-forward * components. */ qd_t FF_GetVqdff(const FF_Handle_t *pHandle); /* * Use this method to get the averaged output values of qd axes * currents PI regulators. */ qd_t FF_GetVqdAvPIout(const FF_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* FEEDFORWARDCTRL_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,596
C
34.649681
105
0.561115
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pidreg_current.h
/** ****************************************************************************** * @file pidreg_current.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 * ****************************************************************************** */ /* pidreg_current.h */ #ifndef _PIDREG_CURRENT_H_ #define _PIDREG_CURRENT_H_ #include "fixpmath.h" typedef struct _PIDREG_CURRENT_s_ { /* configuration */ FIXP_scaled_t Kp_fps; FIXP_scaled_t Wi_fps; float current_scale; float voltage_scale; float pid_freq_hz; /* limits */ fixp24_t Max; fixp24_t Min; /* process */ fixp24_t Err; fixp24_t Up; fixp24_t Ui; fixp30_t Out; fixp24_t compensation; /* bus voltage compensation */ bool clipped; } PIDREG_CURRENT_s; void PIDREG_CURRENT_init( PIDREG_CURRENT_s * pHandle, const float current_scale, const float voltage_scale, const float pid_freq_hz ); fixp30_t PIDREG_CURRENT_run(PIDREG_CURRENT_s* pHandle, const fixp30_t err); bool PIDREF_CURRENT_getClipped( PIDREG_CURRENT_s* pHandle ); float PIDREF_CURRENT_getKp_si( PIDREG_CURRENT_s* pHandle ); float PIDREF_CURRENT_getWi_si( PIDREG_CURRENT_s* pHandle ); void PIDREG_CURRENT_setKp_si(PIDREG_CURRENT_s* pHandle, const float Kp_si); void PIDREG_CURRENT_setWi_si(PIDREG_CURRENT_s* pHandle, const float Wi_si); void PIDREG_CURRENT_setUi_pu( PIDREG_CURRENT_s* pHandle, const fixp30_t Ui); void PIDREG_CURRENT_setCompensation(PIDREG_CURRENT_s* pHandle, const fixp24_t compensation); void PIDREG_CURRENT_setOutputLimits(PIDREG_CURRENT_s* pHandle, const fixp30_t max_pu, const fixp30_t min_pu); #endif /* _PIDREG_CURRENT_H_ */ /* end of pidreg_current.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
2,277
C
31.542857
109
0.614405
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/data_scope.h
/** ****************************************************************************** * @file data_scope.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 * ****************************************************************************** */ /* data_scope.h */ #ifndef _DATA_SCOPE_H_ #define _DATA_SCOPE_H_ /* Functionality: * Read data in RAM in one format, convert to another format, write to another location in RAM * Used to convert internal motor control signals into the correct format to communicate to the PC, or DAC output */ #include "fixpmath.h" #include <stdbool.h> #include <stddef.h> #define DATA_SCOPE_NUMCHANNELS (4) /* ToDo: * Remote control support * - Select pre-defined set of measurements * - Change single channel; * - Select variable (implicitly sets data type, qFmt, full scale, address, maybe default display scale) * - Change display scale (unit/V, e.g. 10A/V, 0.001VpHz/V etc) * - Optional; Change internal parameters, like data qFmt, full scale -- never address, that's protected */ typedef enum _DATA_Datatype_e_ { DATA_DATATYPE_Int32, DATA_DATATYPE_Int16, } DATA_Datatype_e; typedef struct _DATA_SCOPE_CHANNEL_s_ { bool enabled; /* Disable channel while adjusting settings, or not yet configured */ /* data description */ void* pData; /* Location of data in memory */ DATA_Datatype_e datatype; /* Data type in memory */ fixpFmt_t data_qFmt; /* Data qFmt in memory */ float data_fullscale; /* Full scale data range for per unit values, 1.0f default */ /* conversion to volts - calculated from data_scale_f and data description above */ float data_scale_f; /* scale factor for data (V/unit), remembered to prevent unnecessary re-calculations */ FIXP_scaled_t data_scale_fixps; /* scale factor for data (V/unit), derived from data_scale_f */ fixp24_t data_fixp24_volt; /* debug, data in volts */ /* DAC calibration */ fixp15_t dac_scale; /* Number of DAC counts for 1V range */ fixp15_t dac_offset; /* DAC value for 0V output */ /* output */ uint16_t dac_value; /* Value written to the DAC */ } DATA_SCOPE_CHANNEL_s; typedef struct _DATA_SCOPE_Command_s_ { uint32_t command:8; // 7:0 uint32_t channel:8; // 15:8 uint32_t variable:8; // 23:16 uint32_t parameter:8; // 31:24 } DATA_SCOPE_Command_s; typedef union _DATA_SCOPE_Command_u_ { DATA_SCOPE_Command_s bits; uint32_t all; } DATA_SCOPE_Command_u; typedef struct _DATA_SCOPE_Obj_ { DATA_SCOPE_Command_u command; DATA_SCOPE_CHANNEL_s channel[DATA_SCOPE_NUMCHANNELS]; } DATA_SCOPE_Obj; typedef struct _DATA_SCOPE_Obj_* DATA_SCOPE_Handle; extern DATA_SCOPE_Handle DATA_SCOPE_init(void* pMemory, const size_t numWords); extern void DATA_SCOPE_setup(DATA_SCOPE_Handle handle); /* Calculate new values for all active channels */ extern void DATA_SCOPE_run(DATA_SCOPE_Handle handle); extern uint16_t DATA_SCOPE_getSingleChannelValue(DATA_SCOPE_Handle handle, uint16_t channel); extern void DATA_SCOPE_setChannelDacScaleAndOffset(DATA_SCOPE_Handle handle, const uint16_t channel, const fixp15_t scale, const fixp15_t offset); /* Oscilloscope divisions are 1V per division. DataScale is set to x/1V; E.g. dataScale 10.0 would mean 10A/V output. */ extern void DATA_SCOPE_setChannelDataScale(DATA_SCOPE_Handle handle, const uint16_t channel, const float dataScale); #endif /* _DATA_SCOPE_H_ */ /* end of data_scope.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
4,306
C
36.12931
146
0.614259
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/bus_voltage_sensor.h
/** ****************************************************************************** * @file bus_voltage_sensor.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * BusVoltageSensor 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 BusVoltageSensor */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef BUSVOLTAGESENSOR_H #define BUSVOLTAGESENSOR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup BusVoltageSensor * @{ */ /** * @brief BusVoltageSensor handle definition */ typedef struct { SensorType_t SensorType; /*!< It contains the information about the type of instanced bus voltage sensor object. It can be equal to REAL_SENSOR or VIRTUAL_SENSOR */ uint16_t ConversionFactor; /*!< It is used to convert bus voltage from u16Volts into real Volts (V). 1 u16Volt = 65536/ConversionFactor Volts For real sensors ConversionFactor it is equal to the product between the expected MCU voltage and the voltage sensing network attenuation. For virtual sensors it must be equal to 500 */ uint16_t LatestConv; /*!< It contains latest Vbus converted value expressed in u16Volt format */ uint16_t AvBusVoltage_d; /*!< It contains latest available average Vbus expressed in u16Volt format */ uint16_t FaultState; /*!< It contains latest Fault code (#MC_NO_ERROR, #MC_OVER_VOLT or #MC_UNDER_VOLT) */ } BusVoltageSensor_Handle_t; /* Exported functions ------------------------------------------------------- */ uint16_t VBS_GetBusVoltage_d(const BusVoltageSensor_Handle_t *pHandle); uint16_t VBS_GetAvBusVoltage_d(const BusVoltageSensor_Handle_t *pHandle); uint16_t VBS_GetAvBusVoltage_V(const BusVoltageSensor_Handle_t *pHandle); uint16_t VBS_CheckVbus(const BusVoltageSensor_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* BUSVOLTAGESENSOR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
3,251
C
35.539325
85
0.511227
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/max_torque_per_ampere.h
/** ****************************************************************************** * @file max_torque_per_ampere.h * @author Motor Control SDK Team, ST Microelectronics * @brief Maximum torque per ampere (MTPA) control for I-PMSM motors ****************************************************************************** * @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 MTPA */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef MAXTORQUEPERAMPERE_H #define MAXTORQUEPERAMPERE_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup MTPA Maximum Torque Per Ampere Control * @{ */ /* Exported types ------------------------------------------------------------*/ #define SEGMENT_NUM 7U /* coeff no. -1 */ #define MTPA_ARRAY_SIZE SEGMENT_NUM + 1U /** * @brief Handle structure of max_torque_per_ampere.c */ typedef struct { int16_t SegDiv; /**< Segments divisor */ int32_t AngCoeff[MTPA_ARRAY_SIZE]; /**< Angular coefficients table */ int32_t Offset[MTPA_ARRAY_SIZE]; /**< Offsets table */ } MTPA_Handle_t; /* Exported functions ------------------------------------------------------- */ /* Calculates the Id current ref based on input Iq current */ void MTPA_CalcCurrRefFromIq(const MTPA_Handle_t *pHandle, qd_t *Iqdref); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* MAXTORQUEPERAMPERE_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,152
C
28.902777
85
0.48513
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/virtual_bus_voltage_sensor.h
/** ****************************************************************************** * @file virtual_bus_voltage_sensor.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Virtual Bus Voltage Sensor 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 VirtualBusVoltageSensor */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef VIRTUAL_BUSVOLTAGESENSOR_H #define VIRTUAL_BUSVOLTAGESENSOR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "bus_voltage_sensor.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup BusVoltageSensor * @{ */ /** @addtogroup VirtualBusVoltageSensor * @{ */ /** * @brief Virtual Vbus sensor class parameters definition */ typedef struct { BusVoltageSensor_Handle_t _Super; /*!< Bus voltage sensor component handle. */ uint16_t ExpectedVbus_d; /*!< Expected Vbus voltage expressed in digital value hOverVoltageThreshold(digital value)= Over Voltage Threshold (V) * 65536 / 500 */ } VirtualBusVoltageSensor_Handle_t; /* Exported functions ------------------------------------------------------- */ void VVBS_Init(VirtualBusVoltageSensor_Handle_t *pHandle); void VVBS_Clear(VirtualBusVoltageSensor_Handle_t *pHandle); uint16_t VVBS_NoErrors(VirtualBusVoltageSensor_Handle_t *pHandle); /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* VIRTUAL_BUSVOLTAGESENSOR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,438
C
28.743902
85
0.511485
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/virtual_speed_sensor.h
/** ****************************************************************************** * @file virtual_speed_sensor.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Virtual Speed Sensor 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 VirtualSpeedSensor */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef VIRTUALSPEEDSENSOR_H #define VIRTUALSPEEDSENSOR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup VirtualSpeedSensor * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief This structure is used to handle an instance of the Virtual Speed * sensor component. */ typedef struct { SpeednPosFdbk_Handle_t _Super; int32_t wElAccDppP32; /*!< Delta electrical speed expressed in [dpp](measurement_units.md) per speed sampling period to be applied each time is called SPD_calcAvrgMecSpeedUnit multiplied by scaling factor of 65536. */ int32_t wElSpeedDpp32; /*!< Electrical speed expressed in [dpp](measurement_units.md) multiplied by scaling factor 65536. */ uint16_t hRemainingStep; /*!< Number of steps remaining to reach the final speed. */ int16_t hFinalMecSpeedUnit; /*!< Backup of hFinalMecSpeedUnit to be applied in the last step.*/ bool bTransitionStarted; /*!< Retaining information about started Transition status.*/ bool bTransitionEnded; /*!< Retaining information about ended transition status.*/ int16_t hTransitionRemainingSteps; /*!< Number of steps remaining to end transition from Virtual Speed Sensor module to other speed sensor modules */ int16_t hElAngleAccu; /*!< Electrical angle accumulator */ bool bTransitionLocked; /*!< Transition acceleration started */ bool bCopyObserver; /*!< Command to set Virtual Speed Sensor module output same as state observer */ uint16_t hSpeedSamplingFreqHz; /*!< Frequency (Hz) at which motor speed is to be computed. It must be equal to the frequency at which function SPD_calcAvrgMecSpeedUnit is called. */ int16_t hTransitionSteps; /*< Number of steps to perform the transition phase from from Virtual Speed Sensor module to other speed sensor modules. If the Transition PHase should last TPH milliseconds, and the FOC Execution Frequency is set to FEF kHz, then #hTransitionSteps = TPH * FEF */ } VirtualSpeedSensor_Handle_t; /* It initializes the Virtual Speed Sensor component */ void VSS_Init(VirtualSpeedSensor_Handle_t *pHandle); /* It clears Virtual Speed Sensor by re-initializing private variables*/ void VSS_Clear(VirtualSpeedSensor_Handle_t *pHandle); /* It compute a theorical speed and update the theorical electrical angle */ int16_t VSS_CalcElAngle(VirtualSpeedSensor_Handle_t *pHandle, int16_t *pInputVars_str); /* Computes the rotor average theoretical mechanical speed in the unit defined by SPEED_UNIT and * returns it in pMecSpeedUnit */ bool VSS_CalcAvrgMecSpeedUnit(VirtualSpeedSensor_Handle_t *pHandle, int16_t *hMecSpeedUnit); /* It set istantaneous information on VSS mechanical and electrical angle */ void VSS_SetMecAngle(VirtualSpeedSensor_Handle_t *pHandle, int16_t hMecAngle); /* Set the mechanical acceleration of virtual sensor */ void VSS_SetMecAcceleration(VirtualSpeedSensor_Handle_t *pHandle, int16_t hFinalMecSpeedUnit, uint16_t hDurationms); /* Checks if the ramp executed after a VSPD_SetMecAcceleration command has been completed */ bool VSS_RampCompleted(VirtualSpeedSensor_Handle_t *pHandle); /* Get the final speed of last setled ramp of virtual sensor expressed in 0.1Hz */ int16_t VSS_GetLastRampFinalSpeed(VirtualSpeedSensor_Handle_t *pHandle); /* Set the command to Start the transition phase from VirtualSpeedSensor to other SpeedSensor */ bool VSS_SetStartTransition(VirtualSpeedSensor_Handle_t *pHandle, bool bCommand); /* Return the status of the transition phase */ bool VSS_IsTransitionOngoing(VirtualSpeedSensor_Handle_t *pHandle); bool VSS_TransitionEnded(VirtualSpeedSensor_Handle_t *pHandle); /* It sets istantaneous information on rotor electrical angle copied by state observer */ void VSS_SetCopyObserver(VirtualSpeedSensor_Handle_t *pHandle); /* It sets istantaneous information on rotor electrical angle */ void VSS_SetElAngle(VirtualSpeedSensor_Handle_t *pHandle, int16_t hElAngle); /** @} */ /** @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* VIRTUALSPEEDSENSOR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,995
C
45.123077
118
0.612177
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/sto_cordic_speed_pos_fdbk.h
/** ****************************************************************************** * @file sto_cordic_speed_pos_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * State Observer + CORDIC 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 STO_CORDIC_SpeednPosFdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STO_CORDIC_SPEEDNPOSFDBK_H #define STO_CORDIC_SPEEDNPOSFDBK_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "speed_pos_fdbk.h" #include "sto_speed_pos_fdbk.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup SpeednPosFdbk * @{ */ /** @addtogroup STO_CORDIC_SpeednPosFdbk * @{ */ /** * @brief This structure is used to handle an instance of the STO_CORDIC component */ typedef struct { SpeednPosFdbk_Handle_t _Super; int16_t hC1; /*!< State observer constant C1, it can be computed as F1 * Rs(ohm)/(Ls[H] * State observer execution rate [Hz]). */ int16_t hC2; /*!< Variable containing state observer constant C2, it can be computed as F1 * K1/ State observer execution rate [Hz] being K1 one of the two observer gains. */ int16_t hC3; /*!< State observer constant C3, it can be computed as F1 * Max application speed [rpm] * Motor B-emf constant [Vllrms/krpm] * sqrt(2)/ (Ls [H] * max measurable current (A) * State observer execution rate [Hz]). */ int16_t hC4; /*!< State Observer constant C4, it can be computed as K2 * max measurable current (A) / (Max application speed [rpm] * Motor B-emf constant [Vllrms/krpm] * sqrt(2) * F2 * State observer execution rate [Hz]) being K2 one of the two observer gains. */ int16_t hC5; /*!< State Observer constant C5, it can be computed as F1 * max measurable voltage / (2 * Ls [Hz] * max measurable current * State observer execution rate [Hz]). */ int16_t hC6; /*!< State observer constant C6, computed with a specific procedure starting from the other constants. */ int16_t hF1; /*!< State observer scaling factor F1. */ int16_t hF2; /*!< State observer scaling factor F2. */ int16_t hF3; /*!< State observer scaling factor F3. */ uint16_t F3POW2; /*!< State observer scaling factor F3 expressed as power of 2. E.g. if gain divisor is 512 the value must be 9 because 2^9 = 512. */ int32_t Ialfa_est; /*!< Estimated Ialfa current in int32 format. */ int32_t Ibeta_est; /*!< Estimated Ialfa current in int32 format. */ int32_t wBemf_alfa_est; /*!< Estimated B-emf alfa in int32_t format. */ int32_t wBemf_beta_est; /*!< Estimated B-emf beta in int32_t format. */ int16_t hBemf_alfa_est; /*!< Estimated B-emf alfa in int16_t format. */ int16_t hBemf_beta_est; /*!< Estimated B-emf beta in int16_t format. */ int16_t Speed_Buffer[64]; /*!< Estimated speed FIFO, it contains latest bSpeedBufferSize speed measurements. */ uint8_t Speed_Buffer_Index; /*!< Position of latest speed estimation in estimated speed FIFO. */ bool IsSpeedReliable; /*!< Latest private speed reliability information, updated by the *_CalcAvrgMecSpeedUnit() functions. It is true if the speed measurement variance is lower than the threshold corresponding to hVariancePercentage. */ uint8_t ConsistencyCounter; /*!< Counter of passed tests for start-up validation. */ uint8_t ReliabilityCounter; /*!< Counter for reliability check internal to derived class. */ bool IsAlgorithmConverged; /*!< Boolean variable containing observer convergence information. */ int16_t Orig_Speed_Buffer[64]; /*!< Estimated speed FIFO, it contains latest bSpeedBufferSize speed measurements, cordic outputs not modified. */ int16_t Orig_ElSpeedDpp; bool IsBemfConsistent; /*!< Sensor reliability information, updated by the *_CalcAvrgMecSpeedUnit() functions. It is true if the observed back-emfs are consistent with expectations. */ int32_t Obs_Bemf_Level; /*!< Observed back-emf Level. */ int32_t Est_Bemf_Level; /*!< Estimated back-emf Level. */ bool EnableDualCheck; /*!< Consistency check enabler. */ int32_t DppBufferSum; /*!< Summation of speed buffer elements [dpp]. */ int32_t DppOrigBufferSum; /*!< Summation of not modified speed buffer elements [dpp]. */ int16_t SpeedBufferOldestEl; /*!< Oldest element of the speed buffer. */ int16_t OrigSpeedBufferOldestEl; /*!< Oldest element of the not modified speed buffer. */ uint8_t SpeedBufferSizeUnit; /*!< Depth of FIFO used to average estimated speed exported by SPD_GetAvrgMecSpeedUnit. It must be an integer number between 1 and 64. */ uint8_t SpeedBufferSizedpp; /*!< Depth of FIFO used for both averaging estimated speed exported by SPD_GetElSpeedDpp and state observer equations. It must be an integer number between 1 and SpeedBufferSizeUnit. */ uint16_t VariancePercentage; /*!< Parameter expressing the maximum allowed variance of speed estimation. */ uint8_t SpeedValidationBand_H; /*!< It expresses how much estimated speed can exceed forced stator electrical frequency during start-up without being considered wrong. The measurement unit is 1/16 of forced speed. */ uint8_t SpeedValidationBand_L; /*!< It expresses how much estimated speed can be below forced stator electrical frequency during start-up without being considered wrong. The measurement unit is 1/16 of forced speed. */ uint16_t MinStartUpValidSpeed; /*!< 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 Reliability_hysteresys; /*!< Number of reliability failed consecutive tests before a speed check fault is returned to base class. */ int16_t MaxInstantElAcceleration; /*!< maximum instantaneous electrical acceleration (dpp per control period). */ uint8_t BemfConsistencyCheck; /*!< Degree of consistency of the observed back-emfs, it must be an integer number ranging from 1 (very high consistency) down to 64 (very poor consistency). */ uint8_t BemfConsistencyGain; /*!< Gain to be applied when checking back-emfs consistency; default value is 64 (neutral), max value 105 (x1.64 amplification), min value 1 (/64 attenuation) */ uint16_t MaxAppPositiveMecSpeedUnit; /*!< Maximum positive value of rotor speed. Expressed in the unit defined by #SPEED_UNIT. It can be x1.1 greater than max application speed. */ uint16_t F1LOG; /*!< F1 gain divisor expressed as power of 2. E.g. if gain divisor is 512 the value must be 9 because 2^9 = 512. */ uint16_t F2LOG; /*!< F2 gain divisor expressed as power of 2. E.g. if gain divisor is 512 the value must be 9 because 2^9 = 512. */ uint16_t SpeedBufferSizedppLOG; /*!< bSpeedBufferSizedpp expressed as power of 2.E.g. if gain divisor is 512 the value must be 9 because 2^9 = 512. */ bool ForceConvergency; /*!< Variable to force observer convergence. */ bool ForceConvergency2; /*!< Variable to force observer convergence. */ } STO_CR_Handle_t; /* Exported functions ------------------------------------------------------- */ /* It initializes the state observer object */ void STO_CR_Init(STO_CR_Handle_t *pHandle); /* It clears state observer object by re-initializing private variables */ void STO_CR_Clear(STO_CR_Handle_t *pHandle); /* It executes Luenberger state observer and calls CORDIC to compute a new speed * estimation and update the estimated electrical angle */ int16_t STO_CR_CalcElAngle(STO_CR_Handle_t *pHandle, Observer_Inputs_t *pInputs); /* Computes the rotor average mechanical speed in the unit defined by SPEED_UNIT and returns it in pMecSpeedUnit */ bool STO_CR_CalcAvrgMecSpeedUnit(STO_CR_Handle_t *pHandle, int16_t *pMecSpeedUnit); /* Checks whether the state observer algorithm has converged */ bool STO_CR_IsObserverConverged(STO_CR_Handle_t *pHandle, int16_t hForcedMecSpeedUnit); /* It exports estimated Bemf alpha-beta in alphabeta_t format */ alphabeta_t STO_CR_GetEstimatedBemf(STO_CR_Handle_t *pHandle); /* It exports the stator current alpha-beta as estimated by state observer */ alphabeta_t STO_CR_GetEstimatedCurrent(STO_CR_Handle_t *pHandle); /* It exports current observer gains through parameters hC2 and hC4 */ void STO_CR_GetObserverGains(STO_CR_Handle_t *pHandle, int16_t *phC2, int16_t *phC4); /* It allows setting new values for observer gains hC1 and hC2 */ void STO_CR_SetObserverGains(STO_CR_Handle_t *pHandle, int16_t hhC1, int16_t hhC2); /* It computes and update the estimated average electrical speed */ void STO_CR_CalcAvrgElSpeedDpp(STO_CR_Handle_t *pHandle); /* It exports estimated Bemf squared level */ int32_t STO_CR_GetEstimatedBemfLevel(const STO_CR_Handle_t *pHandle); /* It exports observed Bemf squared level */ int32_t STO_CR_GetObservedBemfLevel(const STO_CR_Handle_t *pHandle); /* It enables/disables the bemf consistency check */ void STO_CR_BemfConsistencyCheckSwitch(STO_CR_Handle_t *pHandle, bool bSel); /* It returns the result of the Bemf consistency check */ bool STO_CR_IsBemfConsistent(const STO_CR_Handle_t *pHandle); /* It returns the result of the last variance check */ bool STO_CR_IsSpeedReliable(const STO_Handle_t *pHandle); /* It sets internal ForceConvergency1 to true */ void STO_CR_ForceConvergency1(STO_Handle_t *pHandle); /* It sets internal ForceConvergency2 to true */ void STO_CR_ForceConvergency2(STO_Handle_t *pHandle); /** * @} */ /** * @} */ /** @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /*STO_CORDIC_SPEEDNPOSFDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
12,569
C
57.738317
120
0.574907
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/pwm_common.h
/** ****************************************************************************** * @file pwm_common.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * 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 pwm_curr_fdbk */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef PWMNCOMMON_H #define PWMNCOMMON_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** * @brief The maximum number of needed PWM cycles. verif? */ #define NB_CONVERSIONS 16u /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /* Exported defines ----------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ #ifdef TIM2 /* * Performs the start of all the timers required by the control. * It uses TIM2 as a temporary timer to achieve synchronization between PWM signals. * When this function is called, TIM1 and/or TIM8 must be in a frozen state * with CNT, ARR, REP RATE and trigger correctly set (these settings are * usually performed in the Init method accordingly with the configuration) */ void startTimers(void); #endif /* * Waits for the end of the polarization. If the polarization exceeds * the number of needed PWM cycles, it reports an error. */ void waitForPolarizationEnd(TIM_TypeDef *TIMx, uint16_t *SWerror, uint8_t repCnt, volatile uint8_t *cnt); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* PWMNCOMMON_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,489
C
29
105
0.521896
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/oversampling.h
/** ****************************************************************************** * @file oversampling.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * oversampling 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 oversampling */ #ifndef _OVERSAMPLING_H_ #define _OVERSAMPLING_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "fixpmath.h" #include "drive_parameters.h" #include "parameters_conversion.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup oversampling * @{ */ #define ADC_FIXPFMT (16) /*!< @brief ADC fixp format */ #define DMA_BUFFERS (2) /*!< @brief double buffering constant */ /** * @brief Sample data structure definition */ typedef struct _Samples_t_ { fixp30_t I_R; /*!< @brief Phase R current sample */ fixp30_t I_S; /*!< @brief Phase S current sample */ fixp30_t I_T; /*!< @brief Phase T current sample */ fixp30_t U_R; /*!< @brief Phase R voltage sample */ fixp30_t U_S; /*!< @brief Phase S voltage sample */ fixp30_t U_T; /*!< @brief Phase T voltage sample */ fixp30_t U_DC; /*!< @brief DC bus voltage sample */ } Samples_t; /** * @brief Oversampling channel enum definition */ typedef enum _Oversampling_ChannelName_e_ { OVS_I_R, /*!< @brief index of R current sample */ OVS_I_S, /*!< @brief index of S current sample */ OVS_I_T, /*!< @brief index of T current sample */ OVS_U_R, /*!< @brief index of R voltage sample */ OVS_U_S, /*!< @brief index of S voltage sample */ OVS_U_T, /*!< @brief index of T voltage sample */ OVS_U_DC, /*!< @brief index of DC bus voltage sample */ OVS_THROTTLE, /*!< @brief index of throttle sample */ OVS_TEMP, /*!< @brief index of temperature voltage sample */ OVS_numChannels } Oversampling_ChannelName_e; /** * @brief Oversampling channel data structure definition */ typedef struct _Oversampling_Channel_t_ { uint16_t adc; /*!< @brief ADC for this channel, zero-based */ uint16_t rank; /*!< @brief Rank determines the starting point */ uint16_t tasklen; /*!< @brief Number of ADC Channels this ADC has to sample */ bool single; /*!< @brief Take a single sample at singleIdx, used for low side current shunt measurements */ } Oversampling_Channel_t; /** * @brief DMA double buffering defintion * * The instanciated buffer will be used to store the values transfered from ADCs by the DMA * with double buffering mechanism. * */ typedef uint16_t DMA_ADC_Buffer_t[OVS_LONGEST_TASK * OVS_COUNT * REGULATION_EXECUTION_RATE]; /** * @brief oversampling data structure definition */ typedef struct _Oversampling_t_ { uint16_t count; /*!< @brief oversampling level */ uint16_t divider; /*!< @brief Number of PWM periods per FOC cycle */ int8_t singleIdx; /*!< @brief Oversampling index of single sample */ int8_t readBuffer; /*!< @brief index of the read buffer (double buffering mechanism) */ int8_t writeBuffer; /*!< @brief index of the write buffer (double buffering mechanism) */ fixp30_t current_factor; /*!< @brief phase current scaling factor that will be applied to the value read from ADC */ fixp30_t voltage_factor; /*!< @brief phase voltage scaling factor that will be applied to the value read from ADC */ fixp30_t busvoltage_factor; /*!< @brief DC bus scaling factor that will be applied to the value read from ADC */ DMA_ADC_Buffer_t DMABuffer[DMA_BUFFERS][OVS_NUM_ADCS]; /*!< @brief One DMA buffer per ADC. These are all the same size as the largest required buffer. */ Oversampling_Channel_t Channel[OVS_numChannels]; /*!< @brief Each measurement has an oversampling channel*/ } Oversampling_t; extern Oversampling_t oversampling; void OVERSAMPLING_getMeasurements(Currents_Irst_t* pCurrents_Irst, Voltages_Urst_t* pVoltages_Urst); void OVERSAMPLING_getPotentiometerMeasurements( fixp30_t *value); void OVERSAMPLING_getVbusMeasurements( fixp30_t *value); void OVERSAMPLING_getTempMeasurements( fixp30_t *value); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* _OVERSAMPLING_H_ */
4,972
C
36.11194
121
0.613033
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mc_cordic.h
/** ****************************************************************************** * @file mc_cordic.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 * ****************************************************************************** */ /* mc_cordic.h */ #ifndef _MC_CORDIC_H_ #define _MC_CORDIC_H_ #include <stdint.h> #include "cordic_defs.h" // Number of cycles can be tuned as a compromise between calculation time and precision #define CORDIC_CONFIG_BASE_COSSIN (LL_CORDIC_PRECISION_6CYCLES | LL_CORDIC_SCALE_0 | LL_CORDIC_NBWRITE_2 |\ LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS) /* CORDIC FUNCTION: COSINE only q1.31 */ #define CORDIC_CONFIG_COSINE (CORDIC_CONFIG_BASE_COSSIN | LL_CORDIC_FUNCTION_COSINE) /* CORDIC FUNCTION: SINE only q1.31 */ #define CORDIC_CONFIG_SINE (CORDIC_CONFIG_BASE_COSSIN | LL_CORDIC_FUNCTION_SINE) /* CORDIC FUNCTION: COSINE and SINE q1.31 */ #define CORDIC_CONFIG_COSINE_AND_SINE (CORDIC_CONFIG_BASE_COSSIN | LL_CORDIC_FUNCTION_COSINE | LL_CORDIC_NBREAD_2) /* CORDIC FUNCTION: PHASE q1.31 (Angle and magnitude computation) */ #define CORDIC_CONFIG_PHASE (LL_CORDIC_FUNCTION_PHASE | LL_CORDIC_PRECISION_15CYCLES | LL_CORDIC_SCALE_0 |\ LL_CORDIC_NBWRITE_2 | LL_CORDIC_NBREAD_2 |\ LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS) /* CORDIC FUNCTION: SQUAREROOT q1.31 */ #define CORDIC_CONFIG_SQRT (LL_CORDIC_FUNCTION_SQUAREROOT | LL_CORDIC_PRECISION_3CYCLES | LL_CORDIC_SCALE_1 |\ LL_CORDIC_NBWRITE_1 | LL_CORDIC_NBREAD_1 |\ LL_CORDIC_INSIZE_32BITS | LL_CORDIC_OUTSIZE_32BITS) #define _FIXP30local(A) (int32_t) ((A) * 1073741824.0f) // local macro #define C_ANGLE_CORDIC_TO_PU(angle_cordic) (angle_cordic >> 2) & (_FIXP30local(1.0f)-1) /* scale and wrap cordic angle to per unit */ #define C_ANGLE_PU_TO_CORDIC(angle_pu) (angle_pu << 2) #define C_ANGLE_FP24_PU_TO_CORDIC(angle_pu) (angle_pu << 8) static inline void _CORDIC_polar(const int32_t x, const int32_t y, int32_t *pAngle_pu, int32_t *pMagnitude) { // __disable_irq(); __asm volatile ("cpsid i" : : : "memory"); // WRITE_REG(LCORDIC->CSR, CORDIC_CONFIG_PHASE); LCORDIC->CSR = CORDIC_CONFIG_PHASE; // LL_CORDIC_WriteData(CORDIC, x); // WRITE_REG(CORDICx->WDATA, InData); LCORDIC->WDATA = x; // LL_CORDIC_WriteData(CORDIC, y); // WRITE_REG(CORDICx->WDATA, InData); LCORDIC->WDATA = y; // while (HAL_IS_BIT_CLR(LCORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ while ((LCORDIC->CSR & CORDIC_CSR_RRDY) == 0U); /* Wait for result */ // *pAngle_pu = ANGLE_CORDIC_TO_PU(LL_CORDIC_ReadData(CORDIC)); *pAngle_pu = C_ANGLE_CORDIC_TO_PU(LCORDIC->RDATA); // *pMagnitude = LL_CORDIC_ReadData(CORDIC); *pMagnitude = LCORDIC->RDATA; // __enable_irq(); __asm volatile ("cpsie i" : : : "memory"); } // bit of a mutual inclusion problem for cossin struct type typedef struct { int32_t cos; int32_t sin; } int32_cossin_s; static inline void _CORDIC_30CosSinPU(const int32_t angle_pu, int32_cossin_s *pCosSin) { // __disable_irq(); __asm volatile ("cpsid i" : : : "memory"); // WRITE_REG(LCORDIC->CSR, CORDIC_CONFIG_COSINE_AND_SINE); LCORDIC->CSR = CORDIC_CONFIG_COSINE_AND_SINE; // LL_CORDIC_WriteData(CORDIC, ANGLE_PU_TO_CORDIC(angle_pu)); LCORDIC->WDATA = C_ANGLE_PU_TO_CORDIC(angle_pu); // LL_CORDIC_WriteData(CORDIC, FIXP30(1.0f)); LCORDIC->WDATA = _FIXP30local(1.0f); // while (HAL_IS_BIT_CLR(LCORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ while ((LCORDIC->CSR & CORDIC_CSR_RRDY) == 0U); /* Wait for result */ // pCosSin->cos = LL_CORDIC_ReadData(CORDIC); pCosSin->cos = LCORDIC->RDATA; // pCosSin->sin = LL_CORDIC_ReadData(CORDIC); pCosSin->sin = LCORDIC->RDATA; // __enable_irq(); __asm volatile ("cpsie i" : : : "memory"); } #if 0 // Not implemented yet; will be used in DEMODULATOR_calculateParameters, angle in radians q24, output in q24 static inline void _CORDIC_cos(const int32_t angle_pu, int32_cossin_s *pCosSin) { #if 0 fixp30_t angle_pu = FIXP24_mpy(angle_rad, FIXP30(1.0/M_TWOPI)); WRITE_REG(LCORDIC->CSR, CORDIC_CONFIG_COSINE); LL_CORDIC_WriteData(CORDIC, ANGLE_PU_TO_CORDIC(angle_pu)); LL_CORDIC_WriteData(CORDIC, FIXP24(1.0f)); while (HAL_IS_BIT_CLR(LCORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ return LL_CORDIC_ReadData(CORDIC); #else #warning unchanged cossin code // __disable_irq(); __asm volatile ("cpsid i" : : : "memory"); // WRITE_REG(LCORDIC->CSR, CORDIC_CONFIG_COSINE_AND_SINE); LCORDIC->CSR = CORDIC_CONFIG_COSINE_AND_SINE; // LL_CORDIC_WriteData(CORDIC, ANGLE_PU_TO_CORDIC(angle_pu)); LCORDIC->WDATA = C_ANGLE_PU_TO_CORDIC(angle_pu); // LL_CORDIC_WriteData(CORDIC, FIXP30(1.0f)); LCORDIC->WDATA = _FIXP30local(1.0f); // while (HAL_IS_BIT_CLR(LCORDIC->CSR, CORDIC_CSR_RRDY)); /* Wait for result */ while ((LCORDIC->CSR & CORDIC_CSR_RRDY) == 0U); /* Wait for result */ // pCosSin->cos = LL_CORDIC_ReadData(CORDIC); pCosSin->cos = LCORDIC->RDATA; // pCosSin->sin = LL_CORDIC_ReadData(CORDIC); pCosSin->sin = LCORDIC->RDATA; // __enable_irq(); __asm volatile ("cpsie i" : : : "memory"); #endif } #endif #endif /* _MC_CORDIC_H_ */ /* end of mc_cordic.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
5,762
C
33.716867
133
0.645089
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/usart_aspep_driver.h
/** ****************************************************************************** * @file usart_aspep_driver.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * uart driver for the aspep protocol. * * ****************************************************************************** * @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 * ****************************************************************************** */ #ifndef usart_aspep_driver_h #define usart_aspep_driver_h #include <stdint.h> #include <stdbool.h> /* To be removed no protocol awarness at this level */ typedef struct { USART_TypeDef *USARTx; DMA_TypeDef *rxDMA; DMA_TypeDef *txDMA; uint32_t rxChannel; uint32_t txChannel; } UASPEP_Handle_t; bool UASPEP_SEND_PACKET(void *pHWHandle, void *data, uint16_t length); void UASPEP_RECEIVE_BUFFER(void *pHWHandle, void *buffer, uint16_t length); void UASPEP_INIT(void *pHWHandle); void UASPEP_IDLE_ENABLE(void *pHWHandle); #endif /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
1,501
C
31.652173
85
0.566955
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/speed_torq_ctrl.h
/** ****************************************************************************** * @file speed_torq_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 SpeednTorqCtrlClassic */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef SPEEDNTORQCTRLCLASS_H #define SPEEDNTORQCTRLCLASS_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 * @{ */ /** @addtogroup SpeednTorqCtrlClassic * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief Speed & Torque Control parameters definition */ typedef struct { MC_ControlMode_t Mode; /*!< Modality of STC. It can be one of these two settings: MCM_TORQUE_MODE to enable the Torque mode or MCM_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](measurement_units.md) multiplied by 65536.*/ int32_t TorqueRef; /*!< Current motor torque reference. This value represents actually the Iq current expressed in digit multiplied by 65536. */ 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 #CalcTorqueReference. */ 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](measurement_units.md). */ uint16_t MinAppPositiveMecSpeedUnit; /*!< Application minimum positive value of the rotor mechanical speed. Expressed in the unit defined by [SPEED_UNIT](measurement_units.md). */ int16_t MaxAppNegativeMecSpeedUnit; /*!< Application maximum negative value of the rotor mechanical speed. Expressed in the unit defined by [SPEED_UNIT](measurement_units.md). */ int16_t MinAppNegativeMecSpeedUnit; /*!< Application minimum negative value of the rotor mechanical speed. Expressed in the unit defined by [SPEED_UNIT](measurement_units.md). */ uint16_t MaxPositiveTorque; /*!< Maximum positive value of motor torque. This value represents actually the maximum Iq current expressed in digit. */ int16_t MinNegativeTorque; /*!< Minimum negative 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](measurement_units.md). */ int16_t TorqueRefDefault; /*!< Default motor torque reference. This value represents actually the Iq current reference expressed in digit. */ int16_t IdrefDefault; /*!< Default Id current reference expressed in digit. */ } SpeednTorqCtrl_Handle_t; /* Initializes all the object variables */ void STC_Init(SpeednTorqCtrl_Handle_t *pHandle, PID_Handle_t *pPI, SpeednPosFdbk_Handle_t *SPD_Handle); /* Resets the integral term of speed regulator */ void STC_Clear(SpeednTorqCtrl_Handle_t *pHandle); /* Gets the current mechanical rotor speed reference */ int16_t STC_GetMecSpeedRefUnit(SpeednTorqCtrl_Handle_t *pHandle); /* Gets the current motor torque reference */ int16_t STC_GetTorqueRef(SpeednTorqCtrl_Handle_t *pHandle); /* Sets the mode of the speed and torque controller (Torque mode or Speed mode) */ void STC_SetControlMode(SpeednTorqCtrl_Handle_t *pHandle, MC_ControlMode_t bMode); /* Gets the mode of the speed and torque 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); /* Interrupts the execution of any previous ramp command */ void STC_StopRamp(SpeednTorqCtrl_Handle_t *pHandle); /* Computes the new value of motor torque reference */ int16_t STC_CalcTorqueReference(SpeednTorqCtrl_Handle_t *pHandle); /* Gets the Default mechanical rotor speed reference */ int16_t STC_GetMecSpeedRefUnitDefault(SpeednTorqCtrl_Handle_t *pHandle); /* Returns the Application maximum positive rotor mechanical speed */ uint16_t STC_GetMaxAppPositiveMecSpeedUnit(SpeednTorqCtrl_Handle_t *pHandle); /* Returns the Application minimum negative rotor mechanical speed */ int16_t STC_GetMinAppNegativeMecSpeedUnit(SpeednTorqCtrl_Handle_t *pHandle); /* Checks if the settled speed or torque ramp has been completed */ bool STC_RampCompleted(SpeednTorqCtrl_Handle_t *pHandle); /* Stops the execution of speed ramp */ bool STC_StopSpeedRamp(SpeednTorqCtrl_Handle_t *pHandle); /* Sets in real time the speed sensor utilized by the FOC */ void STC_SetSpeedSensor(SpeednTorqCtrl_Handle_t *pHandle, SpeednPosFdbk_Handle_t *SPD_Handle); /* Returns the speed sensor utilized by the FOC */ SpeednPosFdbk_Handle_t *STC_GetSpeedSensor(SpeednTorqCtrl_Handle_t *pHandle); /* It returns the default values of Iqdref */ qd_t STC_GetDefaultIqdref(SpeednTorqCtrl_Handle_t *pHandle); /* Sets the nominal current */ void STC_SetNominalCurrent(SpeednTorqCtrl_Handle_t *pHandle, uint16_t hNominalCurrent); /* Forces the speed reference to the current speed */ void STC_ForceSpeedReferenceToCurrentSpeed(SpeednTorqCtrl_Handle_t *pHandle); /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* SPEEDNTORQCTRLCLASS_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
7,653
C
44.559524
117
0.626944
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/ramp_ext_mngr.h
/** ****************************************************************************** * @file ramp_ext_mngr.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Ramp Extended Manager 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 RampExtMngr */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef RAMPEXTMNGR_H #define RAMPEXTMNGR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup RampExtMngr * @{ */ /** * @brief RampExtMngr Handle Definition. */ typedef struct { uint32_t FrequencyHz; /*!< Execution frequency expressed in Hz */ int32_t TargetFinal; /*!< Backup of hTargetFinal to be applied in the last step. */ int32_t Ext; /*!< Current state variable multiplied by 32768. */ uint32_t RampRemainingStep; /*!< Number of steps remaining to complete the ramp. */ int32_t IncDecAmount; /*!< Increment/decrement amount to be applied to the reference value at each CalcTorqueReference. */ uint32_t ScalingFactor; /*!< Scaling factor between output value and its internal representation. */ } RampExtMngr_Handle_t; /* Exported functions ------------------------------------------------------- */ void REMNG_Init(RampExtMngr_Handle_t *pHandle); int32_t REMNG_Calc(RampExtMngr_Handle_t *pHandle); bool REMNG_ExecRamp(RampExtMngr_Handle_t *pHandle, int32_t TargetFinal, uint32_t Durationms); int32_t REMNG_GetValue(const RampExtMngr_Handle_t *pHandle); bool REMNG_RampCompleted(const RampExtMngr_Handle_t *pHandle); void REMNG_StopRamp(RampExtMngr_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* RAMPEXTMNGR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
2,663
C
32.721519
112
0.549005
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/current_ref_ctrl.h
/** ****************************************************************************** * @file current_ref_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * six-step current mode current reference PWM generation 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 current_ref_ctrl */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef CURRENTREF_H #define CURRENTREF_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup current_ref_ctrl * @{ */ /* Exported defines ------------------------------------------------------------*/ /* Exported defines ----------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /** * @brief CurrentRef pulse polarity definition */ typedef enum { UP = 0, DOWN = 1, } CurrentRef_PulsePolarity; /** * @brief CurrentRef parameters definition */ typedef struct { TIM_TypeDef * TIMx; /*!< It contains the pointer to the timer used for current reference PWM generation. */ uint32_t RefTimerChannel; /*!< Channel of the timer used the generation. */ } CurrentRef_Params_t; /** * @brief This structure is used to handle the data of an instance of the Current Reference component * */ typedef struct { CurrentRef_Params_t const * pParams_str; uint16_t Cnt; /**< PWM Duty cycle. */ uint16_t StartCntPh; uint16_t PWMperiod; /**< PWM period expressed in timer clock cycles unit: * @f$hPWMPeriod = TimerFreq_{CLK} / F_{PWM}@f$ */ CurrentRef_PulsePolarity pPolarity; } CurrentRef_Handle_t; /* Exported functions --------------------------------------------------------*/ void CRM_Init(CurrentRef_Handle_t *pHandle); void CRM_Clear (CurrentRef_Handle_t *pHandle); void CRM_SetReference(CurrentRef_Handle_t *pHandle, uint16_t hCnt); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* CURRENTREF_H */ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
3,046
C
28.582524
108
0.48851
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/impedcorr.h
/** ****************************************************************************** * @file impedcorr.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 * ****************************************************************************** */ /* impedcorr.h */ #ifndef _IMPEDCORR_H_ #define _IMPEDCORR_H_ #include "fixpmath.h" #include <stddef.h> typedef struct _IMPEDCORR_Params_ { float_t voltageFilterPole_rps; float_t cycleFreq_Hz; float_t fullScaleFreq_Hz; float_t KsampleDelay; float_t fullScaleCurrent_A; float_t fullScaleVoltage_V; } IMPEDCORR_Params; #define IMPEDCORR_SIZE_WORDS (50) /* Size in words, plus a margin */ typedef struct _IMPEDCORR_Obj_ { /* Contents of this structure is not public */ uint16_t reserved[IMPEDCORR_SIZE_WORDS]; } IMPEDCORR_Obj; typedef IMPEDCORR_Obj* IMPEDCORR_Handle; /* Initialization */ extern IMPEDCORR_Handle IMPEDCORR_init(void *pMemory, const size_t size); extern void IMPEDCORR_setParams(IMPEDCORR_Handle pHandle, const IMPEDCORR_Params *pParams); /* Functional */ extern Voltages_Uab_t IMPEDCORR_run(IMPEDCORR_Handle pHandle, const Currents_Iab_t* pIab_pu, const Voltages_Uab_t* pUab_pu, const fixp30_t Fe_pu ); /* Accessors */ extern void IMPEDCORR_getEmf_ab_pu(const IMPEDCORR_Handle handle, Voltages_Uab_t* pEmf_ab); extern void IMPEDCORR_getEmf_ab_filt_pu(const IMPEDCORR_Handle handle, Voltages_Uab_t* pE_ab); extern Voltages_Uab_t IMPEDCORR_getEmf_ab_filt(const IMPEDCORR_Handle handle); extern void IMPEDCORR_getIab_filt_pu(const IMPEDCORR_Handle handle, Currents_Iab_t* pIab_filt); extern Currents_Iab_t IMPEDCORR_getIab_filt(const IMPEDCORR_Handle handle); extern float_t IMPEDCORR_getKSampleDelay(const IMPEDCORR_Handle handle); extern float_t IMPEDCORR_getLs_si(const IMPEDCORR_Handle pHandle); extern FIXP_scaled_t IMPEDCORR_getRs_pu_fps(const IMPEDCORR_Handle handle); extern float_t IMPEDCORR_getRs_si(const IMPEDCORR_Handle pHandle); extern void IMPEDCORR_setKSampleDelay(IMPEDCORR_Handle handle, const float_t value); extern void IMPEDCORR_setLs(IMPEDCORR_Handle handle, const fixp_t Ls_pu, const fixpFmt_t fmt); extern void IMPEDCORR_setRs(IMPEDCORR_Handle handle, const fixp_t Rs_pu, const fixpFmt_t fmt); extern void IMPEDCORR_setLs_si(IMPEDCORR_Handle pHandle, const float_t Ls_H); extern void IMPEDCORR_setRs_si(IMPEDCORR_Handle pHandle, const float_t Rs_Ohm); #endif /* _IMPEDCORR_H_ */ /* end of impedcorr.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
3,081
C
36.13253
95
0.668939
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/rsest.h
/** ****************************************************************************** * @file rsest.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 * ****************************************************************************** */ /* rsest.h */ #ifndef _RSEST_H_ #define _RSEST_H_ #include "fixpmath.h" #include <stddef.h> #include <stdbool.h> typedef struct _RSEST_Params_ { float_t FullScaleCurrent_A; float_t FullScaleVoltage_V; float_t RatedCelcius; /* Temperature @ Rated resistance value (deg C) */ float_t AmbientCelcius; /* Ambient Temperature (deg C) */ float_t RsRatedOhm; float_t MotorSkinFactor; /* Motor skin-factor at choosen injection frequency */ float_t F_calculate_Hz; float_t m_copper_kg; /* Total copper mass for heating estimation */ float_t coolingTau_s; float_t correctionGain; float_t injectGain; } RSEST_Params; typedef struct _RSEST_Obj_ { float_t Tbackground; /* s */ float_t FullScaleImpedance_OHM; /* FullScaleVoltage/FullScaleCurrent */ float_t FullScaleAdmittance_MHO; /* FullScaleCurrent/FullScaleVoltage */ float_t FullScalePower_3ph_W; /* 1.5 * FullScaleCurrent * FullScaleVoltage */ float_t oneoverRs_rated_Mho; /* updated when rated value is changed */ uint16_t decimationCounter; bool update_on; bool current_is_low; bool doBackground; // go command to achieve decimation float_t rs_rated_ohm; // float_t rs_ohm; // read/write in _runBackground FIXP_scaled_t Rs_pu_fps; /* output in pu_fps format */ float_t rs_inject_ohm; // read/write in _runBackground fixp30_t rs_inject_pur; // relative to Rrated fixp_t correctionGain; fixp_t injectGain; /* Skin factor */ fixp_t SkinFactor; // Skinfactor Rac/Rdc normally slightly larger than 1. fixp30_t T_calc; // 1/fBackground = backgroundinterval in seconds, used by _setRsBandwidth_Hz() fixp30_t incRateLimit; fixp30_t incRfactor; uint16_t lpShiftVI; // Low pass filter bitshift for 'VI', voltage x current, used in power calculation uint16_t lpShiftI2t; /* Power-based resistance estimation */ // PowerLP and IsquaredLP are calculated in the interrupt and used in the background to // calculate rs_power_ohm/rs_power_pu_fps. Both are updated only when current is above IsquaredThreshold_pu fixp30_t PowerLP; // Power, low pass filtered (two phase: 2/3 of total power) fixp30_t IsquaredLP; // Squared current, Low pass filtered, required for R = P/I^2 estimation. fixp30_t IsquaredLPt; // faster version of squared current filtered float_t TerminalPowerWatt; // total Terminal Power for all three phases float_t rs_power_ohm; // power-based resistance /* */ fixp20_t ratCelcius_pu; // ambiant temperature (deg C) this is where Rs=Rrated. fixp20_t ambCelcius_pu; fixp30_t ambRfactor; fixp30_t deltaRfactor; /* TempRfactor increment */ fixp30_t maxRfactor; /* Limit outside ZEST operation */ fixp30_t TempRfactor; /* Active Rs/Rrated value */ fixp20_t TempCelcius; // approximate temperature guess fixp30_t Thermal_K; fixp30_t Thermal_Leak; fixp30_t dither; uint32_t debugTestCounter; /* should increase by 1000 counts per second (when flag_debug=true)*/ bool flag_debug; bool synchTemp; fixp20_t debug_TempCelcius; fixp30_t debug_deltaRfactor; fixp30_t debug_TempRfactor; fixp30_t incRfactor_LP; } RSEST_Obj; typedef RSEST_Obj* RSEST_Handle; extern RSEST_Handle RSEST_init(void *pMemory, const size_t size); extern void RSEST_setParams(RSEST_Handle handle, const RSEST_Params *pParams); /* Interrupt function (synchronous with sensorless algorithm) */ extern void RSEST_run(RSEST_Handle handle, const Currents_Iab_t *pIab_pu, const Voltages_Uab_t *pUab_pu); /* Background function (~1 kHz) now spread out in mainloop */ extern void RSEST_runBackground(RSEST_Handle handle); extern void RSEST_runBackSlowed(RSEST_Handle handle, const bool injectActive, const fixp30_t CheckRs, const float_t Rsdelta); /* Getters */ extern bool RSEST_getCurrentIsLow(const RSEST_Handle handle); extern bool RSEST_getDoBackGround(const RSEST_Handle handle); extern fixp30_t RSEST_getRsInjectGainTs(const RSEST_Handle handle); extern float RSEST_getRsInjectOhm(const RSEST_Handle handle); extern float RSEST_getRsOhm(const RSEST_Handle handle); extern float RSEST_getRsPowerOhm(const RSEST_Handle handle); extern FIXP_scaled_t RSEST_getRsRated_fps(const RSEST_Handle handle); extern FIXP_scaled_t RSEST_getRs_pu_fps(const RSEST_Handle handle); extern fixp_t RSEST_getSkinFactor(const RSEST_Handle handle); extern fixp20_t RSEST_getTempCelcius_pu(const RSEST_Handle handle); /* Setters */ extern void RSEST_setAmbientCelcius_pu(RSEST_Handle handle, const fixp20_t value); extern void RSEST_setInjectGain(RSEST_Handle handle, const fixp_t value); extern void RSEST_setRsOhm(RSEST_Handle handle, const float_t rs_ohm); extern void RSEST_setRsRatedOhm(RSEST_Handle handle, const float_t value); extern void RSEST_setRsToRated(RSEST_Handle handle); extern void RSEST_setRs_pu_fps(RSEST_Handle handle, const FIXP_scaled_t rs_pu_fps); extern void RSEST_setSkinFactor(RSEST_Handle handle, const float_t value); extern void RSEST_setTempRfactor(RSEST_Handle handle, const float_t value); extern void RSEST_setUpdate_ON(RSEST_Handle handle, const bool value); #endif /* _RSEST_H_ */ /* end of rsest.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
6,969
C
40.488095
160
0.602095
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/inrush_current_limiter.h
/** ****************************************************************************** * @file inrush_current_limiter.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Inrush Current Limiter component featuring 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 ICL */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __INRUSHCURRENTLIMITER_H #define __INRUSHCURRENTLIMITER_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "bus_voltage_sensor.h" #include "digital_output.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup ICL * @{ */ /* Exported types ------------------------------------------------------------*/ /** * @brief ICL_State_t defines all the existing ICL states of the state machine */ typedef enum { ICL_IDLE, /**< @brief stable state */ ICL_ACTIVATION, /**< @brief transition state */ ICL_ACTIVE, /**< @brief stable state */ ICL_DEACTIVATION, /**< @brief transition state */ ICL_INACTIVE /**< @brief stable state */ } ICL_State_t; /** * @brief ICL_Handle_t is used to handle an instance of the InrushCurrentLimiter component */ typedef struct { BusVoltageSensor_Handle_t *pVBS; /**< @brief Vbus handler used for the automatic ICL component activation/deactivation */ DOUT_handle_t *pDOUT; /**< @brief digital output handler used to physically activate/deactivate the ICL component */ ICL_State_t ICLstate; /**< @brief Current state of the ICL state machine */ uint16_t hICLTicksCounter; /**< @brief Buffer variable containing the number of clock events remaining for next state transition */ uint16_t hICLSwitchDelayTicks; /**< @brief ICL activation/deactivation delay due to switching action of relay (expressed in ICL FSM execution ticks) */ uint16_t hICLChargingDelayTicks; /**< @brief Input capacitors charging delay to be waited before closing relay (expressed in ICL FSM execution ticks)*/ uint16_t hICLVoltageThreshold; /**< @brief Voltage threshold to be reached on Vbus before closing the relay */ } ICL_Handle_t; /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ /* Initializes all the needed ICL component variables */ void ICL_Init(ICL_Handle_t *pHandle, BusVoltageSensor_Handle_t *pVBS, DOUT_handle_t *pDOUT); /* Executes the Inrush Current Limiter state machine */ ICL_State_t ICL_Exec(ICL_Handle_t *pHandle); /* Returns the current state of the ICL state machine. */ ICL_State_t ICL_GetState(ICL_Handle_t *pHandle); /** * @brief Converts the VoltageThreshold configured by the user and updates the * passed ICL's component threshold value in u16V (bus sensor units) * @param pHandle: handler of the current instance of the ICL component * @param hVoltageThreshold : threshold configured by the user to be applied in ICL FSM (expressed in Volts) */ inline static void ICL_SetVoltageThreshold(ICL_Handle_t *pHandle, int16_t hVoltageThreshold) { uint32_t temp; temp = (uint32_t)hVoltageThreshold; temp *= 65536U; temp /= pHandle->pVBS->ConversionFactor; pHandle->hICLVoltageThreshold = (uint16_t)temp; } /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* __INRUSHCURRENTLIMITER_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,313
C
35.559322
156
0.588685
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/profiler.h
/** ****************************************************************************** * @file profiler.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes 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_H_ #define _PROFILER_H_ #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "profiler_types.h" #include "profiler_dcac.h" #include "profiler_fluxestim.h" #include "flash_parameters.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup Profiler * @{ */ /** * @brief Profiler States, lists all the possible profiler state machine states * */ typedef enum _PROFILER_State_e_ { PROFILER_STATE_Idle, /*!< @brief Profiler Idle state */ PROFILER_STATE_DCandACcheck, /*!< @brief DC and AC measurement step */ PROFILER_STATE_FluxEstim, /*!< @brief Flux estimation step after DCAC step complete whitout error */ PROFILER_STATE_Complete, /*!< @brief Profiler complete state set when procedure is finished */ PROFILER_STATE_Error, /*!< @brief Error occurs when profiler procedure is not ready to start, mainly in two cases: - Control Mode is not in Profiling mode - or PWM are not in state forced to zero */ PROFILER_STATE_DCAC_Error, /*!< @brief Error occurs when DCAC profiler step failed, when measured Rs or Ls are out of expected ranges. */ PROFILER_STATE_FluxEstim_Error, /*!< @brief Error occurs when motor fails to spin during profiling */ } PROFILER_State_e; /** * @brief Profiler errors list * */ typedef enum _PROFILER_Error_e_ { PROFILER_ERROR_None, /*!< @brief No error detected */ PROFILER_ERROR_DCAC, /*!< @brief Measured motor parameters are out of expected ranges */ PROFILER_ERROR_FluxEstim, /*!< @brief Resulting speed from the flux observer (HSO) and the open loop frequency does not match */ PROFILER_ERROR_NotReady, /*!< @brief Profiling not ready to start, the procedure is not in a suitable state */ } PROFILER_Error_e; /** * @brief Profiler user commands list * */ typedef enum _PROFILER_Command_e_ { PROFILER_COMMAND_None, /*!< @brief Default state when no user command */ PROFILER_COMMAND_Start, /*!< @brief User command to start the profiler */ PROFILER_COMMAND_Reset, /*!< @brief User command to reset the profiler */ } PROFILER_Command_e; /** * @brief Handle of profiler component * * This structure holds all the parameters needed to implement the profiler * * A pointer on a structure of this type is passed to each * function of the @ref Profiler. */ typedef struct _PROFILER_Obj_ { PROFILER_State_e state; /*!< @brief Profiler state machine */ PROFILER_Command_e command; /*!< @brief User command state */ PROFILER_Error_e error; /*!< @brief Error message to report */ /* Profiler components */ PROFILER_DCAC_Obj dcacObj; /*!< @brief Handle of DCAC object */ PROFILER_FLUXESTIM_Obj fluxestimObj; /*!< @brief Handle of FluxEstim object */ /* Configuration */ float_t PolePairs; /*!< @brief Number of polepairs, for motors without gearbox this is the number of magnets divided by two. For motors with gearbox, this is the number of magnets divided by two, multiplied by the reduction. */ float_t PowerDC_goal_W; /*!< @brief Profiler attempts to reach this power goal during DC ramp-up */ float_t dutyDC; /*!< @brief DC duty applied during profiling */ float_t Idc_A; /*!< @brief DC current (A) used during profiling */ float_t freqEst_Hz; /*!< @brief Open-loop estimated speed */ float_t freqHSO_Hz; /*!< @brief Estimated observer (HSO) speed */ float_t debug_Flux_VpHz; /*!< @brief Estimated flux in V/Hz (for debug only) */ float_t debug_kV; /*!< @brief rpm per Volt DC (for debug only) */ float_t CritFreq_Hz; /*!< @brief Frequency where Rs voltage drop would equal emf at used current level (for debug only) */ float_t injectFreq_Hz; /*!< @brief Injected AC frequency (Hz) during profiling */ float_t fullScaleFreq_Hz; /*!< @brief Full scale frequency (Hz) */ float_t fullScaleVoltage_V; /*!< @brief Full scale voltage (V) */ /* Levels reached */ float_t PowerDC_W; /*!< @brief Power actually reached during DC phase */ /* Identified values */ float_t Rs_dc; /*!< @brief Stator resistance measured using DC duty */ float_t Rs_ac; /*!< @brief Stator resistance measured using AC duty */ float_t R_factor; /*!< @brief Resitance factor = Rs_dc/Rs_ac */ float_t Ld_H; /*!< @brief D-axis inductance measured using AC duty */ float_t Lq_H; /*!< @brief Q-axis inductance is not seperately measured */ float_t Flux_Wb; /*!< @brief Flux measured while running motor */ /* Motor characteristics */ float_t KT_Nm_A; /*!< @brief Torque per Amp (Nm/Apeak) */ float_t Isc_A; /*!< @brief Short circuit current, Flux/Inductance */ /* inital value */ fixp30_t injectFreq_HzZest; /*!< @brief ZeST injected frequency stored before to start profiling */ fixp30_t injectIdZest; /*!< @brief ZeST Injection D current stored before to start profiling */ fixp30_t gainDZest; /*!< @brief ZeST Gain D stored before to start profiling */ fixp30_t gainQZest; /*!< @brief ZeST Gain Q stored before to start profiling */ } PROFILER_Obj; #include "profiler_handle.h" void PROFILER_init(PROFILER_Handle handle, PROFILER_Params* pParams, FLASH_Params_t const *flashParams); void PROFILER_reset(PROFILER_Handle handle, MOTOR_Handle motor); void PROFILER_run(PROFILER_Handle handle, MOTOR_Handle motor); void PROFILER_runBackground(PROFILER_Handle handle, MOTOR_Handle motor); /* Accessors */ float_t PROFILER_getDcAcMeasurementTime(PROFILER_Handle handle); float_t PROFILER_getFlux_Wb(const PROFILER_Handle handle); float_t PROFILER_getFluxEstFreq_Hz(const PROFILER_Handle handle); float_t PROFILER_getFluxEstMeasurementTime(PROFILER_Handle handle); float_t PROFILER_getLd_H(const PROFILER_Handle handle); float_t PROFILER_getPowerGoal_W(const PROFILER_Handle handle); float_t PROFILER_getRs_ac(const PROFILER_Handle handle); float_t PROFILER_getRs_dc(const PROFILER_Handle handle); void PROFILER_setCommand(PROFILER_Handle handle, const PROFILER_Command_e command); void PROFILER_setDcAcMeasurementTime(PROFILER_Handle handle, const float_t time_seconds); void PROFILER_setFluxEstFreq_Hz(PROFILER_Handle handle, const float_t fluxEstFreq_Hz); void PROFILER_setFluxEstMeasurementTime(PROFILER_Handle handle, const float_t time_seconds); void PROFILER_setPolePairs(PROFILER_Handle handle, const float_t polepairs); void PROFILER_setPowerGoal_W(PROFILER_Handle handle, const float_t powerGoal_W); void PROFILER_resetEstimates(PROFILER_Handle handle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* _PROFILER_H_ */
7,928
C
42.092391
144
0.637235
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/flux_weakening_ctrl.h
/** ****************************************************************************** * @file flux_weakening_ctrl.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file provides all definitions and functions prototypes for the * Flux Weakening 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 FluxWeakeningCtrl */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef FLUXWEAKENINGCTRL_H #define FLUXWEAKENINGCTRL_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" #include "pid_regulator.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup FluxWeakeningCtrl * @{ */ /** * @brief Flux Weakening Control Component handle structure */ typedef struct { PID_Handle_t *pFluxWeakeningPID; /**< @brief PI object used for flux weakening. */ PID_Handle_t *pSpeedPID; /**< @brief PI object used for speed control. */ uint16_t hFW_V_Ref; /**< @brief Voltage reference, expressed in tenth ofpercentage points. */ qd_t AvVolt_qd; /**< @brief Average stator voltage in qd reference frame. */ int16_t AvVoltAmpl; /**< @brief Average stator voltage amplitude. */ int16_t hIdRefOffset; /**< @brief Id reference offset. */ uint16_t hMaxModule; /**< @brief Circle limitation maximum allowed module. */ uint16_t hDefaultFW_V_Ref; /**< @brief Default flux weakening voltage reference,tenth of percentage points. */ int16_t hDemagCurrent; /**< @brief Demagnetization current in s16A: Current(Amp) = [Current(s16A) * Vdd micro] / [65536 * Rshunt * Aop]. */ int32_t wNominalSqCurr; /**< @brief Squared motor nominal current in (s16A)^2 where: Current(Amp) = [Current(s16A) * Vdd micro] / [65536 * Rshunt * Aop]. */ uint16_t hVqdLowPassFilterBW; /**< @brief Use this parameter to configure the Vqd first order software filter bandwidth. hVqdLowPassFilterBW = FOC_CurrController call rate [Hz]/ FilterBandwidth[Hz] in case FULL_MISRA_COMPLIANCY is defined. On the contrary, if FULL_MISRA_COMPLIANCY is not defined, hVqdLowPassFilterBW is equal to log with base two of previous definition. */ uint16_t hVqdLowPassFilterBWLOG; /**< @brief hVqdLowPassFilterBW expressed as power of 2. E.g. if gain divisor is 512 the value must be 9 because 2^9 = 512. */ } FW_Handle_t; /* Exported functions ------------------------------------------------------- */ /** * Initializes flux weakening component handler */ void FW_Init(FW_Handle_t *pHandle, PID_Handle_t *pPIDSpeed, PID_Handle_t *pPIDFluxWeakeningHandle); /** * Clears the flux weakening internal variables */ void FW_Clear(FW_Handle_t *pHandle); /** * Computes Iqdref according the flux weakening algorithm */ qd_t FW_CalcCurrRef(FW_Handle_t *pHandle, qd_t Iqdref); /** * Applies a low-pass filter on both Vqd voltage components */ void FW_DataProcess(FW_Handle_t *pHandle, qd_t Vqd); /** * Sets a new value for the voltage reference used by * flux weakening algorithm */ void FW_SetVref(FW_Handle_t *pHandle, uint16_t hNewVref); /** * Returns the present value of target voltage used by flux * weakening algorihtm */ uint16_t FW_GetVref(FW_Handle_t *pHandle); /** * Returns the present value of voltage actually used by flux * weakening algorihtm */ int16_t FW_GetAvVAmplitude(FW_Handle_t *pHandle); /** * Returns the measure of present voltage actually used by flux * weakening algorihtm as percentage of available voltage */ uint16_t FW_GetAvVPercentage(FW_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* FLUXWEAKENINGCTRL_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,004
C
37.206107
118
0.546163
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/mathlib.h
/** ****************************************************************************** * @file mathlib.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 * ****************************************************************************** */ /* mathlib.h */ #ifndef _MATHLIB_H_ #define _MATHLIB_H_ #include <stdint.h> typedef struct _Vector_cossin_s_ { int32_t cos; int32_t sin; } Vector_cossin_s; /* Initialize mathlib by calculating/loading tables */ void MATHLIB_init(void); /* Convert to polar form, calculating angle and magnitude of vector */ void MATHLIB_polar(const int32_t x, const int32_t y, int32_t *angle_pu, int32_t *magnitude); /* Calculate cosine and sine from angle in per-unit */ Vector_cossin_s MATHLIB_cossin(int32_t angle_pu); #endif /* _MATHLIB_H_ */ /* end of mathlib.h */ /************************ (C) COPYRIGHT 2023 Piak Electronic Design B.V. *****END OF FILE****/
1,435
C
29.553191
94
0.542857
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/ntc_temperature_sensor.h
/** ****************************************************************************** * @file ntc_temperature_sensor.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains all definitions and functions prototypes for the * Temperature Sensor 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 TemperatureSensor */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef TEMPERATURESENSOR_H #define TEMPERATURESENSOR_H #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* Includes ------------------------------------------------------------------*/ #include "mc_type.h" /** @addtogroup MCSDK * @{ */ /** @addtogroup TemperatureSensor * @{ */ /** * @brief Structure used for temperature monitoring * */ typedef struct { SensorType_t bSensorType; /**< Type of instanced temperature. This parameter can be REAL_SENSOR or VIRTUAL_SENSOR. */ uint16_t hAvTemp_d; /**< It contains latest available average Vbus. This parameter is expressed in u16Celsius. */ uint16_t hExpectedTemp_d; /**< Default set when no sensor available (ie virtual sensor) */ uint16_t hExpectedTemp_C; /**< Default value when no sensor available (ie virtual sensor). This parameter is expressed in Celsius. */ uint16_t hFaultState; /**< Contains latest Fault code. This parameter is set to #MC_OVER_TEMP or #MC_NO_ERROR. */ uint16_t hLowPassFilterBW; /**< used to configure the first order software filter bandwidth. hLowPassFilterBW = NTC_CalcBusReading call rate [Hz]/ FilterBandwidth[Hz]. */ uint16_t hOverTempThreshold; /**< Represents the over voltage protection intervention threshold. This parameter is expressed in u16Celsius through formula: hOverTempThreshold = (V0[V]+dV/dT[V/°C]*(OverTempThreshold[°C] - T0[°C]))* 65536 / MCU supply voltage. */ uint16_t hOverTempDeactThreshold; /**< Temperature threshold below which an active over temperature fault is cleared. This parameter is expressed in u16Celsius through formula: hOverTempDeactThreshold = (V0[V]+dV/dT[V/°C]*(OverTempDeactThresh[°C] - T0[°C]))* 65536 / MCU supply voltage. */ int16_t hSensitivity; /**< NTC sensitivity This parameter is equal to MCU supply voltage [V] / dV/dT [V/°C] */ uint32_t wV0; /**< V0 voltage constant value used to convert the temperature into Volts. This parameter is equal V0*65536/MCU supply Used in through formula: V[V]=V0+dV/dT[V/°C]*(T-T0)[°C] */ uint16_t hT0; /**< T0 temperature constant value used to convert the temperature into Volts Used in through formula: V[V]=V0+dV/dT[V/°C]*(T-T0)[°C] */ uint8_t convHandle; /*!< handle to the regular conversion. */ } NTC_Handle_t; /* Initialize temperature sensing parameters */ void NTC_Init(NTC_Handle_t *pHandle); /* Clear static average temperature value */ void NTC_Clear(NTC_Handle_t *pHandle); /* Temperature sensing computation */ uint16_t NTC_CalcAvTemp(NTC_Handle_t *pHandle, uint16_t rawValue); /* Get averaged temperature measurement expressed in u16Celsius */ uint16_t NTC_GetAvTemp_d(const NTC_Handle_t *pHandle); /* Get averaged temperature measurement expressed in Celsius degrees */ int16_t NTC_GetAvTemp_C(NTC_Handle_t *pHandle); /* Get the temperature measurement fault status */ uint16_t NTC_CheckTemp(const NTC_Handle_t *pHandle); /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /* __cpluplus */ #endif /* TEMPERATURESENSOR_H */ /************************ (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
4,939
C
40.512605
119
0.530877
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/MCSDK_v6.2.0-Full/MotorControl/MCSDK/MCLib/Any/Inc/r1_dd_pwm_curr_fdbk.h
/** ****************************************************************************** * @file r1_dd_pwm_curr_fdbk.h * @author Motor Control SDK Team, ST Microelectronics * @brief This file contains common definitions for Single Shunt, Dual Drives * PWM and Current Feedback components. ****************************************************************************** * @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_R1_DD */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __R1_DD_PWM_CURR_FDBK_H #define __R1_DD_PWM_CURR_FDBK_H #define GPIO_NoRemap_TIM1 ((uint32_t)(0)) #define SAME_FREQ 0u /** @addtogroup MCSDK * @{ */ /** @addtogroup pwm_curr_fdbk * @{ */ /** @defgroup PWMnCurrFdbk_R1_DD Single Shunt Dual Drive Parameters * * @brief Common definitions for Single Shunt, Dual Drives PWM and Current Feedback components * * @{ */ /** * @brief R1 DD parameters definition */ typedef struct { TIM_TypeDef *TIMx; /*!< Timer used for PWM generation. It should be TIM1 or TIM8*/ TIM_TypeDef *TIMx_2; /*!< Auxiliary timer used for single shunt */ ADC_TypeDef *ADCx_Inj; /*!< ADC Peripheral used for phase current sampling */ ADC_TypeDef *ADCx_Reg; /*!< ADC Peripheral used for regular conversion */ GPIO_TypeDef *pwm_en_u_port; GPIO_TypeDef *pwm_en_v_port; GPIO_TypeDef *pwm_en_w_port; uint32_t pwm_en_u_pin; uint32_t pwm_en_v_pin; uint32_t pwm_en_w_pin; uint16_t Tafter; /*!< It is the sum of dead time plus rise time express in number of TIM clocks.*/ uint16_t Tbefore; /*!< It is the value of sampling time expressed in numbers of TIM clocks.*/ uint16_t TMin; /*!< It is the sum of dead time plus rise time plus sampling time express in numbers of TIM clocks.*/ uint16_t HTMin; /*!< It is the half of TMin value.*/ uint16_t TSample; /*!< It is the sampling time express in numbers of TIM clocks.*/ uint16_t MaxTrTs; /*!< It is the maximum between twice of rise time express in number of TIM clocks and twice of sampling time express in numbers of TIM clocks.*/ uint16_t DeadTime; /*!< 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*/ uint8_t FreqRatio; /*!< It is used in case of dual MC to synchronize times. It 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 InstanceNbr; /*!< Instance number with reference to PWMC base class. It is necessary to properly synchronize TIM8 with TIM1 at peripheral initializations */ uint8_t IChannel; /*!< ADC channel used for conversion of current. 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*/ bool IsFirstR1DDInstance; /*!< Specifies whether this object is the first R1DD instance or not.*/ LowSideOutputsFunction_t LowSideOutputs; /*!< Low side or enabling signals generation method are defined here.*/ } R1_DDParams_t; /** * @} */ /** * @} */ /** * @} */ #endif /*__R1_DD_PWM_CURR_FDBK_H*/ /******************* (C) COPYRIGHT 2023 STMicroelectronics *****END OF FILE****/
5,608
C
43.515873
95
0.465763
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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/LegDay/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; } Iab->a = -Iab->a; Iab->b = -Iab->b; 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; } Iab->a = -Iab->a; Iab->b = -Iab->b; 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; } wAux = -wAux; 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,832
C
29.438028
132
0.600583
Tbarkin121/GuardDog/stm32/MotorDrive/LegDay/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/LegDay/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/LegDay/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