基于stm32f103rct6的高级定时器PWM输出
硬件部分
本文基于stm32f103rct6芯片,以TIM1为例,实现 CH3N 即 PB15 引脚的 PWM 输出
代码部分
" Timer1.h "
#ifndef __TIMER1_H
#define __TIMER1_H
void TIM1_PWM_Init(u16 arr, u16 psc);
#endif
" Timer1.c "
#include "stm32f10x.h" // Device header
#include "timer1.h"
//arr:自动重装值
//psc:时钟预分频数
void TIM1_PWM_Init(u16 arr, u16 psc) {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); //使能定时器1时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO, ENABLE); //使能GPIO外设和AFIO复用功能模块时钟
//设置该引脚为复用输出功能
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15; //TIM1_CH3N
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);//初始化GPIO
//初始化TIM1
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = arr; //设置在下一个更新事件装入活动的自动重装载寄存器周期的值
TIM_TimeBaseStructure.TIM_Prescaler = psc; //设置用来作为TIMx时钟频率除数的预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; //重复计数设置
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); //根据TIM_TimeBaseInitStruct中指定的参数初始化TIMx的时间基数单位
//初始化TIM1 Channel1 PWM模式
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式1
//TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable; //比较输出N使能
TIM_OCInitStructure.TIM_Pulse = 3600; //设置待装入捕获比较寄存器的脉冲值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
//TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_High; //输出N极性:TIM输出比较N极性高
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; //空闲状态下输出比较:TIM输出比较空闲状态下为低
//TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCNIdleState_Reset; //空闲状态下输出N比较:TIM输出比较N空闲状态下为低
//初始化TIM1 Channel3 PWM模式
TIM_OCInitStructure.TIM_Pulse = 3600; //设置待装入捕获比较寄存器的脉冲值
TIM_OC3Init(TIM1, &TIM_OCInitStructure); //根据T指定的参数初始化外设TIM1 OC3
TIM_Cmd(TIM1,ENABLE);
TIM_CtrlPWMOutputs(TIM1,ENABLE);
}
“main.c”
#include "stm32f10x.h" // Device header
#include "timer1.h"
int main(void)
{
TIM1_PWM_Init( 100, 90 );//设置ARR和PSC
TIM_SetCompare3( TIM1, 75 ); //设置CCR,此处CCR/ARR的值即为占空比
while(1){
}
}