Transforming encoder value to servo position
Core/Src/main.c uint16_t percentToServoPosition(bool mode, uint16_t percent)
{
uint16_t ret =0;
float div = (percent/100.0f);
if(mode)
ret =START_POSITION + div * (END_POSITION - START_POSITION);
else
ret =END_POSITION - div * (END_POSITION - START_POSITION);
return ret;
}
The function transforms the encoder value to an appropriate servo position. Values are scaled within the range from START_POSITION to END_POSITION, enabling precise servo position control.
Setting servo position
Core/Src/main.c void setServoPosition(uint16_t position)
{
__HAL_TIM_SET_COMPARE(&htim10,TIM_CHANNEL_1, position);
}
The function sets the servo position by updating the timer compare register of TIM10. The value passed to the function is directly the PWM pulse value.
Main control loop
Core/Src/main.c __HAL_TIM_SET_COMPARE(&htim10,TIM_CHANNEL_1, START_POSITION);
uint16_t servoPosition = 0;
while (1)
{
pulse_count = TIM4->CNT; // przepisanie wartosci z rejestru timera
positions = pulse_count/4; // zeskalowanie impulsow do liczby stabilnych pozycji walu enkodera
servoPosition = percentToServoPosition(true, pulse_count);
setServoPosition(servoPosition);
}
The main loop reads the encoder counter, scales the value and sets the appropriate servo position. The value is transformed by the percentToServoPosition function and set by setServoPosition.