当我们输出一段脉冲信号的时候就可以调节舵机的角度
我们可以从原理图可以看到舵机的脚在PA6
从芯片手册我们又可以看到PA6对应TIM3_CH1,并且不用开启部分重映像就能使用
新建Servo.c存放PWM初始化
配置PWM
void Servo_TIM3_Init(u16 arr,u16 psc)
{
//开启TIM3的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,ENABLE); //PWM脚在GPIOA上,并开启AFIO复用
//配置端口
//PA6
GPIO_InitTypeDef GPIO_Structure;
GPIO_Structure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Structure.GPIO_Pin = GPIO_Pin_6; //TIM1_CH1 | TIM1_CH4
GPIO_Structure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_Structure);
//初始化TIM3
TIM_TimeBaseInitTypeDef TIM3_Structure;
TIM3_Structure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM3_Structure.TIM_Prescaler = psc; //设置用来作为TIMx时钟频率除数的预分频值
TIM3_Structure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
TIM3_Structure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数
TIM_TimeBaseInit(TIM3,&TIM3_Structure);
//初始化TIM3_CH1 PWM模式
TIM_OCInitTypeDef TIM_OC_Structure;
TIM_OC_Structure.TIM_OCMode = TIM_OCMode_PWM2; //选择定时器模式:TIM脉冲宽度调制模式2
TIM_OC_Structure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OC_Structure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性:TIM输出比较极性低
TIM_OC1Init(TIM3,&TIM_OC_Structure);
TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_Enable);
TIM_Cmd(TIM3,ENABLE);
}
封装角度函数
这样直接输入想要的角度就行了,不用再每次看手册来设置
void Servo_TIM_SetCompare1(uint16_t Num)
{
switch(Num)
{
case 0: TIM_SetCompare1(TIM3,25);break;
case 45:TIM_SetCompare1(TIM3,50);break;
case 90:TIM_SetCompare1(TIM3,75);break;
case 135:TIM_SetCompare1(TIM3,100);break;
case 180:TIM_SetCompare1(TIM3,125);break;
default:TIM_SetCompare1(TIM3,25);break;
}
}
main.c进行调用测试
//初始化PWM
Servo_TIM3_Init(999,1439);
//直接调节TIM3通道1的占空比就可以摇头,加上我们前面封装的函数直接输入角度就行
Servo_TIM_SetCompare1(TIM3,0);
delay_ms(900);
Servo_TIM_SetCompare1(TIM3,45);
delay_ms(900);
Servo_TIM_SetCompare1(TIM3,90);
delay_ms(900);