stm32中如何设置PWM通道输出占空比

我们可通过一个例子来学习

eg: 假设我要PWM波的TIM3以1KHZ的频率运行(系统时钟 = 72MHZ)
且此时我们把arr = 99(即百分制),这样方便后面占空比的划分;

因为:TIM3的计数时钟/(arr+1) = 1KHZ
求得 TIM3的计数时钟=100KHZ
(psc+1)=系统时钟/TIM3的计数时钟 = 720

开始求占空比:
占空比和CCR与ARR有关即 *占空比 = (CCR/ARR)100%

例如:
TIM3_CCR1=20
则(TIM3_CCR1/ TIM3_ARR)* 100%= 20%
TIM3_CCR1=50
则(TIM3_CCR2/ TIM3_ARR)* 100% =50%
TIM3_CCR1=72
则 (TIM3_CCR3/ TIM3_ARR)* 100% = 72%
TIM3_CCR1=99.9
则 (TIM3_CCR4/ TIM3_ARR)* 100% = 99.9%

下面设置TIM3_CH1在PA6输出占空比为20%的PWM波:

 void TIM3_PWM_Init(void)
 {
 GPIO_InitTypeDef GPIO_InitStructure;
 TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
 TIM_OCInitTypeDef  TIM_OCInitStructure;
 
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); // 使能GPIOB时钟
 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
 // 配置IO模式
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;// 复用推挽复用输出
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
 GPIO_Init(GPIOA, &GPIO_InitStructure);			
 //初始化TIM3的计数模式、分频值、重装载值等
 TIM_TimeBaseStructure.TIM_Period = 99;  //ARR
 TIM_TimeBaseStructure.TIM_Prescaler = 719; //PSC
 TIM_TimeBaseStructure.TIM_ClockDivision = 0;
 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;// 向上计数模式 
 TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

 /*TIM3_CH1输出占空比为20%的PWM波的定时配置*/
 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;// 选择定时器模式:TIM脉冲宽度调制模式1
 TIM_OCInitStructure.TIM_OutputState =TIM_OutputState_Enable;// 比较输出使能
 TIM_OCInitStructure.TIM_Pulse = 20;  //CCR
 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;// 输出极性:TIM输出比较极性高
 TIM_OC1Init(TIM3, &TIM_OCInitStructure);

 TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);// 使能TIM3在OC1上的预装载寄存器
 
 TIM_Cmd(TIM3, ENABLE);//使能TIM3时钟




如有错误请指正!!!

你可能感兴趣的:(stm32学习)