Files
Gamble/MPU6050/APP/servo.c
2023-12-18 14:36:22 +08:00

100 lines
2.5 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "servo.h"
#include "Delay.h"
void Servo_Init(void)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //使能TIM2时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //使能GPIOA时钟
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_4;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//配置PA1PA2为复用输出模式输出速度为50MHZ
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//开启TIM2内部时钟
TIM_InternalClockConfig(TIM2);
//配置TIM2
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; //时钟分频
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //计数方式向上计数
TIM_TimeBaseInitStructure.TIM_Period = 100 - 1; //ARR 自动重装载值
TIM_TimeBaseInitStructure.TIM_Prescaler = 72 - 1; //PSC 预分频器
TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; //
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseInitStructure);
//输出通道配置
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;//配置PWM模式1
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//有效极性为高电平
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0; //CCR
TIM_OC1Init(TIM2, &TIM_OCInitStructure); //初始化通道1 PA0
TIM_OC2Init(TIM2, &TIM_OCInitStructure); //初始化通道2 PA1
TIM_OC3Init(TIM2, &TIM_OCInitStructure); //初始化通道3 PA2
TIM_Cmd(TIM2, ENABLE); //使能定时器2
}
void Rotate(u8 a,u8 b,u8 c)
{
TIM_SetCompare1(TIM2,a);
TIM_SetCompare2(TIM2,b);
TIM_SetCompare3(TIM2,c);
}
//修改通道2比较值
// TIM_SetCompare2(TIM2, Compare);
//正转
void Rotate_clockwise(void)
{
Rotate(10,0,0);
delay_ms(10);
Rotate(10,10,0);
delay_ms(10);
Rotate(0,10,0);
delay_ms(10);
Rotate(0,10,10);
delay_ms(10);
Rotate(0,0,10);
delay_ms(10);
Rotate(10,0,10);
}
//反转
void Rotate_counterclockwise(void)
{
Rotate(0,10,0);
delay_ms(10);
Rotate(10,10,0);
delay_ms(10);
Rotate(10,0,0);
delay_ms(10);
Rotate(10,0,10);
delay_ms(10);
Rotate(0,0,10);
delay_ms(10);
Rotate(0,10,10);
}
//停止
void Rotate_stop(void)
{
Rotate(0,0,0);
}
//刹车
void Rotate_shache(void)
{
Rotate(3,0,0);
}