void dj_init()
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_6;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;//复用推挽输出
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_7;
GPIO_Init(GPIOA,&GPIO_InitStructure);
TIM_TimeBaseInitStructure.TIM_Period=2000; //自动装载值
TIM_TimeBaseInitStructure.TIM_Prescaler=720; //分频系数
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //设置向上计数模式
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure);
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OC1Init(TIM3,&TIM_OCInitStructure); //输出比较通道1初始化
TIM_OC2Init(TIM3,&TIM_OCInitStructure); //输出比较通道2初始化
TIM_OC1PreloadConfig(TIM3,TIM_OCPreload_Enable); //使能TIMx在 CCR1 上的预装载寄存器
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable); //使能TIMx在 CCR2 上的预装载寄存器
TIM_ARRPreloadConfig(TIM3,ENABLE);//使能预装载寄存器
TIM_Cmd(TIM3,ENABLE); //使能定时器
TIM_SetCompare1(TIM3,1850);//舵机运动到中间位置 1950-1850-1750 0.9°/1
TIM_SetCompare2(TIM3,1850);
}
void dj_move_Angle(int Level,int Verticality)//按角度移动 水平、竖直 以0.9°的倍数输入最准确 -90--+90
{
int Angle2=1850+Level/0.9;
int Angle1=1850-Verticality/0.9;
TIM_SetCompare2(TIM3,Angle2);//通道2PA7 水平方向
TIM_SetCompare1(TIM3,Angle1);//通道1PA6 竖直方向
}
void dj_move_Angle(int Level,int Verticality)//按角度移动 水平、竖直 以1.35°的倍数输入最准确 -135--135
{
int Angle2=1850+Level/1.35;
int Angle1=1850-Verticality/1.35;
TIM_SetCompare2(TIM3,Angle2);//通道2PA7 水平方向
TIM_SetCompare1(TIM3,Angle1);//通道1PA6 竖直方向
}
STM32控制270度或180度舵机
于 2023-11-30 19:43:48 首次发布