How to controll esc with pwm signal from RC controller
- January 20, 2024
- 2 replies
- 4218 views
So i have this simple code for pwm input for the rc controller :
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef* htim)
{
if (htim->Instance == TIM2)
{
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
{
capture_value[0] = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_1);
if (capture_value[0])
{
frequency[0] = SystemCoreClock / capture_value[0];
duty_cycle[0] = 10000 * HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2) / capture_value[0];
}
} }
How to take the value of capture_value and controll an ESC with it? i feel like i tried anything at this point and it just wont work. Here is my last attempt
uint32_t mappedValue[0];
uint32_t pwmInput[0];
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min + 1) / (in_max - in_min + 1) + out_min;
}
// Function to set PWM duty cycle for motors
void setMotorPWM(uint32_t motorIndex, uint32_t pwmValue)
{
// Ensure motorIndex is within bounds
if (motorIndex < 4)
{
// Set PWM duty cycle for the corresponding motor channel
if (motorIndex == 0)
__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_1, pwmValue);
else if (motorIndex == 1)
__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_2, pwmValue);
else if (motorIndex == 2)
__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_3, pwmValue);
else if (motorIndex == 3)
__HAL_TIM_SET_COMPARE(&htim1, TIM_CHANNEL_4, pwmValue);
// Optionally, update the duty_cycle array
duty_cycle[motorIndex] = pwmValue;
}
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
// Assuming this callback is triggered based on the PWM input from the RC controller
if (htim == &htim1)
{
// Read the PWM input value from your RC controller (you need to implement this part)
pwmInput[0] = duty_cycle[0];
// Map the PWM input to the desired range for your motors
mappedValue[0] = map(pwmInput[0], 0, 2000, 50, 150);
// Set the PWM duty cycle for the first motor
setMotorPWM(0, mappedValue[0]);
}
}
------------
int main(void)
{
/* USER CODE BEGIN 1 */
// Initialize your hardware peripherals (TIM, GPIO, etc.) and system
// Start PWM for all motor channels
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_2);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_3);
HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_4);
EDIT: I am using STM32F07G - disc1
