2023-04-11 05:25 PM
I calculate the speed of a motor with the method input capture calbback() then I have the recurring equation of the motor control,U(k)=U(k-1)-0.04*e(k-1)+0.12*e (k)
e(k) error = reference speed - current speed
the problem that the command in the infinite loop changes even the engine stopped:
any suggestion please?
int PWM_PERIOD=100;
int pwmMin=0;
int resolution=10;
float speedMotor2;
float speedMotor1;
volatile float em1=0;
volatile float um1=0;
volatile float u1m1=0;
volatile float e1m1=0;
int tensionMax=19.5;
/* USER CODE END 0 */
volatile uint32_t IC1_Val1 = 0;
volatile uint32_t IC1_Val2 = 0;
volatile uint32_t IC2_Val1 = 0;
volatile uint32_t IC2_Val2 = 0;
volatile int Difference1 = 0;
volatile int Difference2=0;
volatile int Difference=0;
volatile int Is_First_Captured = 0;
volatile int Is_First_Captured1=0;
/* Measure Frequency */
volatile float frequency1 = 0;
volatile float frequency2 = 0;
int TIMCLOCK=50000000;
int PRESCALAR=50;
float firstTick=0;
float periodeMotor1=0;
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM2){
if(htim->Channel==HAL_TIM_ACTIVE_CHANNEL_1 && speedMotor1 ==0)
{
if (Is_First_Captured==0) // if the first rising edge is not captured
{
IC1_Val1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); // read the first value
Is_First_Captured = 1; // set the first captured as true
}
else
{
IC1_Val2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1); // read second value
if (IC1_Val2 > IC1_Val1)
{
Difference1 = IC1_Val2-IC1_Val1;
}
else if (IC1_Val1 > IC1_Val2)
{
Difference1 = (0xffff - IC1_Val1) + IC1_Val2;
}
float refClock = TIMCLOCK/(PRESCALAR);
frequency1 = refClock/Difference1;
speedMotor1 = (frequency2 * 60) / ( resolution);
Is_First_Captured = 0; // set it back to false
}
}
}}
uint16_t commande_to_pwm_value(float commande)
{
uint16_t pwm_value = (uint16_t)((commande / tensionMax) * PWM_PERIOD);
if (pwm_value > PWM_PERIOD)
{
pwm_value = PWM_PERIOD;
}
if (pwm_value <0)
{
pwm_value = pwmMin;
}
return pwm_value;
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_TIM1_Init();
MX_TIM2_Init();
/* USER CODE BEGIN 2 */
TIM1->CCR1 = 100;
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
HAL_TIM_IC_Start_IT(&htim2,TIM_CHANNEL_1);
while (1)
{
int vitesseRef=300;
em1=(vitesseRef-speedMotor1);
//commande m1
um1=u1m1+0.1287*em1-0.0429*e1m1;
u1m1=um1;
e1m1=em1;
float cm1=commande_to_pwm_value(um1);
TIM2->CCR1=cm1;
}
}