大家好,我在用PA8做普通IO输出口使用,然后做PWM口使用,初始化顺序是开始设置输出口,然后设置为PWM口,为何PWM口失效,不起作用,程序如下:
void PwmIoOut(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* 使能GPIOA时钟 */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
/* 配置LED相应引脚PA8 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
下面是初始化PWM口
void TIM1PwmInit(FunctionalState flag)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, flag/*ENABLE*/);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, flag/*ENABLE*/); //使能定时器1
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource8, GPIO_AF_2);// 第2 功能TIM1
//**************************************************************************
// 定时器1设置: 2分频,24KHz频率,
//**************************************************************************
TIM_TimeBaseStructure.TIM_Period = 999; // 设置自动重装周期值
TIM_TimeBaseStructure.TIM_Prescaler = 1; //2分频
TIM_TimeBaseStructure.TIM_ClockDivision = 0;//设置时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;// 向上计数
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);//初始化定时1
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;//PWM2模式
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;//比较输出使能
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;//TIM_OCPolarity_High;//输出高
TIM_OCInitStructure.TIM_Pulse = 5; // 300-1 30%占空比
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);//
/* TIM1 enable counter */
TIM_Cmd(TIM1, flag/*ENABLE*/);
TIM_CtrlPWMOutputs(TIM1,flag/*ENABLE*/);
}
main()
{
PwmIoOut();
TIM1PwmInit(); //PWM失效,不能起作用,请大家分析原因,谢谢
} |