大家先看懂这张图,我们就是根据这张图 实现定时器产生PWM控制舵机旋转,本次采用的STM32F1单片机控制S90舵机,直接COPY就可以使用,经过本人实测,采用PB13 定时器1PWM通道1实现本次的控制,从0度控制180度旋转改变占空比实现舵机不同角度的控制占空比越准,那么控制舵机角度更精准,本次仅仅实现了舵机控制,精度未测试,不在本次测试范围内。主要注意定时器配置和IO口的复用功能。千万不要当普通IO口使用。
static void TIM_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_ResetBits(GPIOB,GPIO_Pin_13);
}
static void Advance_TIM_Config(void)
{
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1,ENABLE);
TIM_TimeBaseStructure.TIM_Period= (200-1);
TIM_TimeBaseStructure.TIM_Prescaler= (7200-1);
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter=0;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High;
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set;
TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Reset;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_Cmd(TIM1, ENABLE);
TIM_CtrlPWMOutputs(TIM1, ENABLE);
}
void TIM_Init(void)
{
TIM_GPIO_Config();
Advance_TIM_Config();
}
void main()
{
u16 delay_time = 1000;
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
TIM_Init();
while(1)
{
delay_ms(delay_time);
TIM_SetCompare1(TIM1, 25);
delay_ms(delay_time);
TIM_SetCompare1(TIM1, 5);
delay_ms(delay_time);
}
}
[百度云下载链接] 链接:https://pan.baidu.com/s/1zUEgEFqh0OTUbKQHLL7m_Q 提取码:1234
|