STM32C8T6發(fā)送控制信號給電機驅動,電機驅動控制步進電機。
電機驅動:控制一個步進電機轉動,使用一路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);
}