stm32的通用定时器有TIM2、TIM3、TIM4、TIM5,每个定时器都有独立的四个通道可以作为:输入捕获、输出比较、PWM输出、单脉冲模式输出等。stm32除了基本定时器,其他定时器都能输出PWM。PWM 常见于控制舵机和电机。今天学习了stm32单片机的通用定时器如何输出PWM控制舵机,现总结如下:
步骤总结:
配置GPIO结构体(此处GPIO为具有复用功能的引脚)->配置通用定时器结构体->配置定时器输出PWM结构体->使能预加载寄存器->使能定时器->配置PWM比较值->控制舵机
ServoMotor.c:
#include "stm32f10x.h"#include "ServoMotor.h"void ServoMotor_Config(void){GPIO_InitTypeDef GPIO_MOTORInitStructure;TIM_TimebaseInitTypeDef Tim_MOTORInitStructure;TIM_OCInitTypeDef Time_PWMInitStructure;//开时钟RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);//部分重映射GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE);//配置GPIO结构体GPIO_MOTORInitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_MOTORInitStructure.GPIO_Pin = GPIO_Pin_5;GPIO_MOTORInitStructure.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOB,&GPIO_MOTORInitStructure);//配置通用定时器结构体Tim_MOTORInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;Tim_MOTORInitStructure.TIM_CounterMode = TIM_CounterMode_Up;Tim_MOTORInitStructure.TIM_Period = 200-1;Tim_MOTORInitStructure.TIM_Prescaler = 7200-1;TIM_TimebaseInit(TIM3,&Tim_MOTORInitStructure);//配置定时器输出PWM结构体Time_PWMInitStructure.TIM_OCMode = TIM_OCMode_PWM1;Time_PWMInitStructure.TIM_OutputState = TIM_OutputState_Enable;Time_PWMInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;TIM_OC2Init(TIM3,&Time_PWMInitStructure);//使能预加载寄存器TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable);//使能定时器TIM_Cmd(TIM3,ENABLE);}
main.c:
#include "stm32f10x.h"#include "ServoMotor.h"void delay(uint16_t time){uint16_t i = 0;while(time -- ){i = 12000;while(i -- );}}int main(void){ServoMotor_Config();uint16_t pwm = 155;while(1){for(pwm = 195; pwm >=175; pwm-=5){TIM_SetCompare2(TIM3,pwm);delay(500);}}}
如有错误,请批评指正