#include "main.h"
static void SG90_TIM_Init(void);
static void SG90_Angle(float angle);
static void SG90_Angle2(float angle);
SG90ClassStruct SG90Class = {
SG90_TIM_Init,
SG90_Angle,
SG90_Angle2
};
// 使用哪个通道
#define USE_TIM_CH1
#define USE_TIM_CH2
#if 0
#define SG90_TIM TIM2
#define SG90_TIM_CLK RCC_APB1Periph_TIM2
#define SG90_GPIO_PORT GPIOA
#define SG90_GPIO_CLK RCC_APB2Periph_GPIOA
#ifdef USE_TIM_CH1
#define SG90_GPIO_PIN GPIO_Pin_0
#endif
#ifdef USE_TIM_CH2
#define SG90_GPIO_PIN2 GPIO_Pin_1
#endif
#else
#define SG90_TIM TIM3
#define SG90_TIM_CLK RCC_APB1Periph_TIM3
#define SG90_GPIO_PORT GPIOA
#define SG90_GPIO_CLK RCC_APB2Periph_GPIOA
#ifdef USE_TIM_CH1
#define SG90_GPIO_PIN GPIO_Pin_6
#endif
#ifdef USE_TIM_CH2
#define SG90_GPIO_PIN2 GPIO_Pin_7
#endif
#endif
// PWM初始化 10000-1,144-1
static void SG90_TIM_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(SG90_GPIO_CLK, ENABLE); //使能GPIO外设时钟使能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(SG90_TIM_CLK, ENABLE); //时钟使能
//设置该引脚为复用输出功能,输出PWM脉冲波形
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
#ifdef USE_TIM_CH1
GPIO_InitStructure.GPIO_Pin = SG90_GPIO_PIN;
GPIO_Init(SG90_GPIO_PORT, &GPIO_InitStructure);
#endif
#ifdef USE_TIM_CH2
GPIO_InitStructure.GPIO_Pin = SG90_GPIO_PIN2;
GPIO_Init(SG90_GPIO_PORT, &GPIO_InitStructure);
#endif
//定时器初始化
TIM_TimeBaseStructure.TIM_Period = 10000-1; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler = 144-1; //设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(SG90_TIM, &TIM_TimeBaseStructure); //根据指定的参数初始化TIMx的时间基数单位
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //选择定时器模式:TIM脉冲宽度调制模式2
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_Pulse = 0; //设置待装入捕获比较寄存器的脉冲值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性:TIM输出比较极性高
#ifdef USE_TIM_CH1
TIM_OC1Init(SG90_TIM, &TIM_OCInitStructure); //根据TIM_OCInitStruct中指定的参数初始化外设TIMx
TIM_OC1PreloadConfig(SG90_TIM, TIM_OCPreload_Enable); //CH1预装载使能
#endif
#ifdef USE_TIM_CH2
TIM_OC2Init(SG90_TIM, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(SG90_TIM, TIM_OCPreload_Enable);
#endif
TIM_ARRPreloadConfig(SG90_TIM, ENABLE); //使能TIMx在ARR上的预装载寄存器
TIM_Cmd(SG90_TIM, ENABLE); //使能TIMx
TIM_CtrlPWMOutputs(SG90_TIM,ENABLE); //MOE 主输出使能
}
// CH1舵机角度
static void SG90_Angle(float angle)
{
angle = (uint16_t)(50.0 * angle / 9.0 + 250.0);
TIM_SetCompare1(SG90_TIM, angle);
}
// CH2舵机角度
static void SG90_Angle2(float angle)
{
angle = (uint16_t)(50.0 * angle / 9.0 + 250.0);
TIM_SetCompare2(SG90_TIM, angle);
}
- 1
- 2
前往页