STM32输出PWM

Posted sypspace

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了STM32输出PWM相关的知识,希望对你有一定的参考价值。

最近要用STM32来输出PWM,花了一个晚上写完了,记录一下

(我用的是STM32F303CCT6)

1.打开定时器时钟

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

2.打开输出引脚的GPIO时钟

RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

3.配置相应引脚为 AF模式(具体AFx要看手册)

GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_2);

4.初始化输出引脚为 AF模式, 推挽输出, 上拉, 速度为GPIO_Speed_Level_3

GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF; //PA6
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_Level_3;
GPIO_Init(GPIOA, &GPIO_InitStruct);

 

5.定时器设置( 频率 = 72000000÷(arr+1)÷(psc+1))

TIM_TimeBaseStruct.TIM_Period = 999; //arr
TIM_TimeBaseStruct.TIM_Prescaler = 1439;//psc
TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStruct.TIM_RepetitionCounter = 0;//重复溢出多少次进中断
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStruct);

6.定时器通道设置 PWM模式1, 输出极性高, 允许输出

TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStruct);

7.打开定时器

TIM_Cmd(TIM3, ENABLE);

8.设置占空比 Duty  =  pwmval  ÷  arr

TIM_SetCompare1(TIM3, 99);// pwmval Duty = arr/pwmval

9.全部代码如下

GPIO_InitTypeDef GPIO_InitStruct;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_2);

GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF; 
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_Level_3;
GPIO_Init(GPIOA, &GPIO_InitStruct);

TIM_TimeBaseStruct.TIM_Period = 999; //arr
TIM_TimeBaseStruct.TIM_Prescaler = 1439;// psc 
TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStruct.TIM_RepetitionCounter = 0;//重复溢出多少次进中断
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStruct);

TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStruct);
TIM_OC2Init(TIM3, &TIM_OCInitStruct);

TIM_Cmd(TIM3, ENABLE);

TIM_SetCompare1(TIM3, 99);//pwmval

 

在STM32中,PWM输出的 频率,占空比,模式 有好几个不同的参数设置

 













































以上是关于STM32输出PWM的主要内容,如果未能解决你的问题,请参考以下文章

如何让stm32产生多路输出 PWM 最好有代码

stm32 tim pwm的问题

stm32h750pwm有多少个

STM32 通用定时输出PWM

STM32通用定时器PWM输出

STM32无PWM输出