本帖最后由 ddllxxrr 于 2023-4-10 09:30 编辑
本来想用N32G430芯片来驱动步进电机,可是手头上正好有一个N32G45XVL-STB开发板,于是就用它来驱动一下。
原理是一样地。我用定时器输出通道来输出PWM波,用板子上的按键来控制允许和方向。
那么到板子上就是PA6输出脉冲,PA2,PA3控制允许和方向。
void GPIO_Configuration(void)
{
GPIO_InitType GPIO_InitStructure;
/* GPIOA Configuration:TIM3 Channel1, 2, 3 and 4 as alternate function push-pull */
GPIO_InitStructure.Pin = GPIO_PIN_6 ;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitPeripheral(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.Pin = GPIO_PIN_2 | GPIO_PIN_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitPeripheral(GPIOA, &GPIO_InitStructure);
}
main.c如下:
int main(void)
{
/* System Clocks Configuration */
RCC_Configuration();
/* GPIO Configuration */
GPIO_Configuration();
/* -----------------------------------------------------------------------
TIM3 Configuration: generate 4 PWM signals with 4 different duty cycles:
TIM3 Frequency = TIM3 counter clock/(AR + 1)
TIM3 Channel1 duty cycle = (TIM3_CCR1/ TIM3_ARR)* 100
TIM3 Channel2 duty cycle = (TIM3_CCR2/ TIM3_ARR)* 100
TIM3 Channel3 duty cycle = (TIM3_CCR3/ TIM3_ARR)* 100
TIM3 Channel4 duty cycle = (TIM3_CCR4/ TIM3_ARR)* 100
----------------------------------------------------------------------- */
/* Compute the prescaler value */
PrescalerValue = (uint16_t)(SystemCoreClock / 24000000) - 1;
/* Time base configuration */
TIM_TimeBaseStructure.Period = 665;
TIM_TimeBaseStructure.Prescaler = PrescalerValue;
TIM_TimeBaseStructure.ClkDiv = 0;
TIM_TimeBaseStructure.CntMode = TIM_CNT_MODE_UP;
TIM_InitTimeBase(TIM3, &TIM_TimeBaseStructure);
/* PWM1 Mode configuration: Channel1 */
TIM_OCInitStructure.OcMode = TIM_OCMODE_PWM1;
TIM_OCInitStructure.OutputState = TIM_OUTPUT_STATE_ENABLE;
TIM_OCInitStructure.Pulse = CCR1_Val;
TIM_OCInitStructure.OcPolarity = TIM_OC_POLARITY_HIGH;
TIM_InitOc1(TIM3, &TIM_OCInitStructure);
TIM_ConfigOc1Preload(TIM3, TIM_OC_PRE_LOAD_ENABLE);
/* TIM3 enable counter */
TIM_Enable(TIM3, ENABLE);
while (1)
{
if(GPIO_ReadInputDataBit(GPIOA,GPIO_PIN_4)==0)
{
GPIO_SetBits(GPIOA,GPIO_PIN_2);
GPIO_ResetBits(GPIOA,GPIO_PIN_3);
}
else if((GPIO_ReadInputDataBit(GPIOA,GPIO_PIN_5)==0))
{
GPIO_ResetBits(GPIOA,GPIO_PIN_2);
GPIO_ResetBits(GPIOA,GPIO_PIN_3);
}
else if((GPIO_ReadInputDataBit(GPIOA,GPIO_PIN_6)==0))
{
GPIO_SetBits(GPIOA,GPIO_PIN_2);
GPIO_SetBits(GPIOA,GPIO_PIN_3);
}
}
}
需要注意的是选择第几个PWM通道的函数是:
TIM_InitOc1(TIM3, &TIM_OCInitStructure);
如果选第二个通道那么就写为:
TIM_InitOc2(TIM3, &TIM_OCInitStructure);
当然得初始化通道2
先上个照片:
视频
|