如何在带定时器的STM32F103上为控制伺服电机生成PWM
C代码
我想通过PWM控制伺服电机
我从ADC获得值,然后计算得出PWM占空比

流程图
获取VR的值-> ADC模块(将模数转换为数字)->计算PWM占空比->使用计时器为控制伺服电机生成PWM-> while循环

对不起我的英语。

最佳答案

该代码假设APB1时钟= 72MHz
Servo_Target为八分之一微秒,因此4000表示1ms(低伺服位置),而8000表示2ms(高伺服位置)
警告:PWM频率为463Hz,因此您不能将此设置用于模拟伺服。它适用于无刷调节器。如果要使用模拟伺服,则必须更改TIM_Prescaler,TIM_Period
并考虑对Servo_Target值的影响

TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode   = TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_Period        = 8192;
TIM_TimeBaseStructure.TIM_Prescaler     = 18;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_Cmd(TIM2, ENABLE);  // Start PWM Timer
TIM_OCInitStructure.TIM_OCMode      = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity  = TIM_OCPolarity_High;

// THIS IS THE WIDTH in 1/8 us
TIM_OCInitStructure.TIM_Pulse       = Servo_Target;

/* PWM1 Mode configuration: TIM2 Channel1 */
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);

/* PWM1 Mode configuration: TIM2 Channel2 */
TIM_OC2Init(TIM2, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);

// add OC3_ and OC4_ for 3rd and 4th channels
TIM_ARRPreloadConfig(TIM2, ENABLE);

10-08 17:33