关于普通定时器与高级定时器的 PWM输出的初始化的区别

时间:2021-05-24 11:21:05

不管是普通定时器还是高级定时器,你用哪个通道,就在程序里用OC多少。比如CH3对应OC3

TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; 
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; 
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; 
TIM_OCInitStructure.TIM_Pulse=42;
TIM_OC4Init(TIM1, &TIM_OCInitStructure);

TIM_OC4PreloadConfig(TIM1, TIM_OCPreload_Enable);

之前就是因为这个没有弄清楚,PWM波形没有输出,这是在通用定时器里出现的错误。

等把这个错误解决了以后,就开弄高级定时器,没有想到在通用定时器可以出来的PWM程序,在高级定时器就没有输出,只是改变了定时器以及对应的IO口。经过各种查找,发现是少了一条语句

TIM_CtrlPWMOutputs(TIM1,ENABLE);

加上这条语句后,就有输出了。

这就是通用定时器与高级定时器的PWM输出的区别。

如果不想用定时器的时钟源作为时基,而是想用外部的脉冲来作为时基,那就要加一条语句

TIM_ETRClockMode2Config(TIM3, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0);

并且是将外部脉冲接在对应定时器的ETR引脚上。

下面是基本代码

void TIM3_PWM_Init(u16 arr,u16 psc)
{

GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);  
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD|RCC_AHB1Periph_GPIOA, ENABLE);

GPIO_PinAFConfig(GPIOD,GPIO_PinSource2,GPIO_AF_TIM3); 
GPIO_PinAFConfig(GPIOC,GPIO_PinSource9,GPIO_AF_TIM3);

TIM_ETRClockMode2Config(TIM3, TIM_ExtTRGPSC_OFF, TIM_ExtTRGPolarity_NonInverted, 0);

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOD, &GPIO_InitStructure);

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; 
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; 
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz; 
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; 
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ; 
GPIO_Init(GPIOC,&GPIO_InitStructure);

TIM_TimeBaseStructure.TIM_Prescaler=psc; 
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; 
TIM_TimeBaseStructure.TIM_Period=arr;
TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseStructure);

TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; 
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; 
TIM_OCInitStructure.TIM_Pulse=1;
TIM_OC4Init(TIM3, &TIM_OCInitStructure);

TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);

TIM_ARRPreloadConfig(TIM3,ENABLE);

TIM_Cmd(TIM3, ENABLE);

TIM_CtrlPWMOutputs(TIM3,ENABLE);

}

现在还有个问题就是高级定时器1为什么不能通过PA8(通道 1)输出PWM,处理器是stm32f4ZGT6.