1、控制过程程序:
- 首先,新建bsp_servo.h与bsp_servo.c文件
本实验使用TIM3的输出通道1,在bsp_servo.h文件中定义宏
#define GENERAL_TIM TIM3
#define GENERAL_TIM_APBxClock_FUN RCC_APB1PeriphClockCmd
#define GENERAL_TIM_CLK RCC_APB1Periph_TIM3
#define GENERAL_TIM_Prescaler (72000-1)
#define GENERAL_TIM_Period (20-1)
#define GENERAL_TIM_CH1_GPIO_CLK RCC_APB2Periph_GPIOA
#define GENERAL_TIM_CH1_PORT GPIOA
#define GENERAL_TIM_CH1_PIN GPIO_Pin_6
- 之后来到bsp_servo.c文件,配置GPIO端口为复用,输出端口为PA6,具体使用哪个端口可以参考对应型号的data sheet。
static void GENERAL_TIM_GPIO_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(GENERAL_TIM_CH1_GPIO_CLK, ENABLE);
GPIO_InitStructure.GPIO_Pin = GENERAL_TIM_CH1_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GENERAL_TIM_CH1_PORT, &GPIO_InitStructure);
}
使用TIM功能的PWM模式
static void GENERAL_TIM_Mode_Config(void)
{
GENERAL_TIM_APBxClock_FUN(GENERAL_TIM_CLK,ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period=GENERAL_TIM_Period;
TIM_TimeBaseStructure.TIM_Prescaler= GENERAL_TIM_Prescaler;
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter=0;
TIM_TimeBaseInit(GENERAL_TIM, &TIM_TimeBaseStructure);
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OC1Init(GENERAL_TIM, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(GENERAL_TIM, TIM_OCPreload_Enable);
TIM_Cmd(GENERAL_TIM, ENABLE);
}
定义一个初始化函数,同时初始化时基与输出比较
void GENERAL_TIM_Init(void)
{
GENERAL_TIM_GPIO_Config();
GENERAL_TIM_Mode_Config();
}
void Delay(__IO uint32_t nCount)
{
for(; nCount != 0; nCount--);
}
#define SOFT_DELAY Delay(0x0FFFFF);
- 前面将TIM3配置为PWM模式1,即为向上计数,CNT<CCR时通道为有效电平,这一段时间即为脉冲宽度,ARR=(200-1),要使舵机在0°到180°旋转,CRR应在10-20
int main(void)
{
GENERAL_TIM_Init();
while(1)
{
for(int i = 5;i < 26;i++)
{
TIM_SetCompare1(GENERAL_TIM , i);
SOFT_DELAY;
}
}
}
2、连线图效果如图所示
|