#include "stm32f10x.h" // Device header
#include "delay.h"
void Tim3_PWM()
{
GPIO_InitTypeDef led;
TIM_TimeBaseInitTypeDef Tim_struct; //配置时基结构体
TIM_OCInitTypeDef TIM3_chal2; //TIM3的2通道
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO|RCC_APB2Periph_GPIOB,ENABLE); //使能GPIOB与复用AFIO
GPIO_PinRemapConfig(GPIO_PartialRemap_TIM3,ENABLE); //更改指定引脚的复用功能
led.GPIO_Mode=GPIO_Mode_AF_PP; //设置输出端口为复用推挽
led.GPIO_Pin=GPIO_Pin_5;
led.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOB,&led);
Tim_struct.TIM_ClockDivision=0; //时钟划分
Tim_struct.TIM_CounterMode=TIM_CounterMode_Up; //向上计数
Tim_struct.TIM_Period=899; //自动转载值 ARR
Tim_struct.TIM_Prescaler=0; //预分频值 PSC
//Tim_struct.TIM_RepetitionCounter //重复计数器
TIM_TimeBaseInit(TIM3,&Tim_struct); //时基结构体初始化
TIM3_chal2.TIM_OCMode=TIM_OCMode_PWM2; //设置PWM模式2,
TIM3_chal2.TIM_OCNPolarity=TIM_OCPolarity_High; //设置捕获极性,在上升沿高电平时捕获
TIM3_chal2.TIM_OutputState=TIM_OutputState_Enable;
TIM_OC2Init(TIM3,&TIM3_chal2);
TIM_OC2PreloadConfig(TIM3,TIM_OCPreload_Enable); //使能CCR2预转载值
TIM_Cmd(TIM3,ENABLE); //使能定时器
}
int main(void)
{
unsigned int pwm =0;
unsigned char dir =1;
Tim3_PWM();
while (1)
{
Delay_ms(10);
if(dir)
{
pwm++;
}
else
{
pwm--;
}
if(pwm>300)
{
dir=0;
}
if(pwm==0)
{
dir=1;
}
TIM_SetCompare2(TIM3,pwm);
}
}
TIM_SetCompare2(TIM3,pwm); //设置比较值pwm,与装载值arr进行比较,
CCR寄存器:捕获比较寄存器;
关于PWM模式一/二的选择
TIM3_chal2.TIM_OCMode=TIM_OCMode_PWM2; //设置PWM模式2,
CNT寄存器:计数寄存器
PWM模式二在计数值 > CCR时输出为有效电平即输出低电平
PWM模式一在计数值 < CCR时输出为有效电平即输出高电平