I use a STM32F103 chip and I try to synchronize two DC motors using inputcapture, I read the time difference between the rising edge of each sensor hall of effect,how can I update the pwm of the two motors. please check with me the pg
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance==TIM1){
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
{
if (Is_First_Captured==0) // if the first rising edge is not captured
{
IC1_Val1 =TIM1->CNT; // read the first value of the first sensor
Is_First_Captured = 1; // set the first captured as true
}
}
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4)
{
if (Is_First_Captured1==0) // if the first rising edge is not captured
{
IC2_Val1 = TIM1->CNT; // read the first value of the seconde sensor
Is_First_Captured1 = 1; // set the first captured as true
}
Is_First_Captured1 = 0; // set it back to false
}
}
}
// synchronize tow motors
sync_motors(void){
time_diff = IC1_Val1 - IC2_Val1;
// Si le capteur 1 a été activé avant le capteur 2, on augmente le PWM du moteur 1
if (time_diff > 0)
{
sync_error = time_diff;
// Augmentation du PWM du moteur 1
motor1_pwm += 0.1*sync_error;
if (motor1_pwm > 1000)
{
motor1_pwm = 1000;
}
TIM3->CCR1 = motor1_pwm;
//Réduction du PWM du moteur 2
motor2_pwm -= 0.1*sync_error;
if (motor2_pwm < 0)
{
motor2_pwm = 0;
}
TIM2->CCR1 = motor2_pwm;
}
// Si le capteur 2 a été activé avant le capteur 1, on augmente le PWM du moteur 2
else if (time_diff < 0)
{
sync_error = -time_diff;
// Augmentation du PWM du moteur 2
motor2_pwm += 0.01*sync_error;
if (motor2_pwm > 1000)
{
motor2_pwm = 1000;
}
TIM2->CCR1 = motor2_pwm;
// Réduction du PWM du moteur 1
motor1_pwm -= 0.1*sync_error;
if (motor1_pwm < 0)
{
motor1_pwm = 0;
}
TIM3->CCR1 = motor1_pwm;
}
}
int main(void)
{......
while (1)
{
sync_motors();
}
}
