问题描述
- STM32定时器1控制电机输出两路PWM波形问题
-
本人刚学stm32,用定时器1的CH1和CH2输出pwm波形是不知道为什么没有高电平输出,电机根本不转求大家看看
#include "include.h"
/*
硬件连接:
(PE9->EN1---TIME1_CH1 右) (PE11->EN2---TIME1_CH2 左) PA4->INT4 PA5->INT3 PA6->INT2 PA7->INT1
*//*0011 1010--->,,EN1,EN2,INT4,INT3... */
void PWM_Foward(void)
{GPIO_SetBits(GPIOA , GPIO_Pin_4|GPIO_Pin_6);
GPIO_ResetBits(GPIOA , GPIO_Pin_5|GPIO_Pin_7);
}/*0011 0101--->,,EN1,EN2,INT4,INT3... */
void PWM_Back(void)
{GPIO_SetBits(GPIOA , GPIO_Pin_5|GPIO_Pin_7); GPIO_ResetBits(GPIOA , GPIO_Pin_4|GPIO_Pin_6);
}
/*0011 0110--->,,EN1,EN2,INT4,INT3... */
void PWM_Left(void)
{GPIO_SetBits(GPIOA , GPIO_Pin_5|GPIO_Pin_6); GPIO_ResetBits(GPIOA , GPIO_Pin_4|GPIO_Pin_7);
}
/*0011 1001--->,,EN1,EN2,INT4,INT3... */
void PWM_Right(void)
{GPIO_SetBits(GPIOA , GPIO_Pin_4|GPIO_Pin_7);
GPIO_ResetBits(GPIOA , GPIO_Pin_5|GPIO_Pin_6);
}/*参考固件库使用手册247*/
void Timer1_Config(void)
{TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
/*Time1_Init*/
/*将寄存器重新设为缺省值*/
TIM_DeInit(TIM1);
/*预分频为72M/3600=20KHZ*/
TIM_TimeBaseStructure.TIM_Prescaler=3600-1;
/*时钟分割,采样频率设置,滤掉外界高频抖动,无外部设备介入设为0*/
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
/*装载值:20 , 20KHZ/20=1Khz,计数值为1ms*/
TIM_TimeBaseStructure.TIM_Period=200;
/*向上计数*/
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
/*重复计数器,只限制在0X00--0XFF,stm32中文手册209*/
TIM_TimeBaseStructure.TIM_RepetitionCounter=0;
TIM_TimeBaseInit(TIM1 , &TIM_TimeBaseStructure);/*设置通道*/ /*PWM输出通道选择,向上计数时,1:若计数值<装载值,为有效电平,否则无效,通道2相反*/ TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2; /*正向通道有效,反向通道无效*/ TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; /*占空比预设为10,为0.5ms,占空比不能超过装载值即周期*/ TIM_OCInitStructure.TIM_Pulse=100; /*输出极性,及在计数阶段IO口的电平*/ TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_High; TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset; TIM_OC1Init(TIM1 , &TIM_OCInitStructure); TIM_OC2Init(TIM1 , &TIM_OCInitStructure); TIM_Cmd(TIM1 , ENABLE); /*定时器1作为主输出*/ TIM_CtrlPWMOutputs(TIM1 , ENABLE);
}
void PWM_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* (PE9->EN1---TIME1_CH1 右) (PE11->EN2---TIME1_CH2 左)*/
/*GPIO_Init*/RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE);
/*IO口的复用:作为输入输出是打开IO口模式复用,作为第二功能比如I2C时打开时钟复用*/ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE|RCC_APB2Periph_AFIO , ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1 , ENABLE); /*INT1----INT4*/ GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7; GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; GPIO_Init(GPIOA , &GPIO_InitStructure); /*将TIM1完全重映射到GPIOE*/ GPIO_PinRemapConfig(GPIO_FullRemap_TIM1 ,ENABLE); GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; GPIO_Init(GPIOE , &GPIO_InitStructure); Timer1_Config();
}