STM32C8T6控制步进电机
扫描二维码
随时随地手机看文章
STM32C8T6发送控制信号给电机驱动,电机驱动控制步进电机。
电机驱动:控制一个步进电机转动,使用一路PWM信号和一路方向信号,根据pwm信号的频率控制步进电机的转速,方向信号控制步进转动的方向。
void SteppingMotor_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; //TIM2的1通道输出pwm波形控制电机,对应PA0口
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2; //步进电机正反转和使能控制口
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//定义PWM频率
TIM_TimeBaseStructure.TIM_Prescaler =719; //预分频值
TIM_TimeBaseStructure.TIM_Period =99; //重装值,这里输出的pwm频率为1KHZ
TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); //时基单元配置
//设定占空比
TIM_OCStructInit(& TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_Pulse =50; //P的占空比
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM2, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM2,ENABLE);
TIM_Cmd(TIM2, ENABLE);
TIM_CtrlPWMOutputs(TIM2, ENABLE);
}
void SteppingMotorControl(u8 dir) //正反转控制
{
if(0==dir)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_1); //反转
}
else
{
GPIO_SetBits(GPIOA,GPIO_Pin_1); //正转
}
}
void EnableSteppingMotor(void)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_2);
}
void DisableSteppingMotor(void)
{
GPIO_SetBits(GPIOA,GPIO_Pin_2);
}