STM32F103定时器输出PWM

2024-07-01 12:25:47 浏览数 (2)

 1.注意事项

        IM_TimeBaseInitTypeDef结构体里面有5个成员,TIM6和TIM7的寄存器里面只TIM_Prescaler和TIM_Period,所以使用TIM6和TIM7的时候只需初始化这两个成员即可,另外三个成员是通用定时器和高级定时器才有。

结构体当中的对比:

typedef struct

{ TIM_Prescaler 都有

        TIM_CounterMode TIMx,x[6,7]没有,其他都有

        TIM_Period 都有

        TIM_ClockDivision TIMx,x[6,7]没有,其他都有

        TIM_RepetitionCounter TIMx,x[1,8,15,16,17]才有

}TIM_TimeBaseInitTypeDef;

2. PWM信号 周期和占空比的计算

// ARR :自动重装载寄存器的值

// CLK_cnt:计数器的时钟,等于 Fck_int / (psc 1) = 72M/(psc 1)

// PWM 信号的周期 T = ARR * (1/CLK_cnt) = ARR(PSC 1) / 72M

// 占空比P=CCR/(ARR 1)

pwm.c

代码语言:javascript复制
void Tim3Pwm1Init(void)
{
    GPIO_InitTypeDef     GPIO_InitStructure;
    TIM_TimeBaseInitTypeDef     TIM_TimeBaseStructure;
    TIM_OCInitTypeDef  TIM_OCInitStructure;
    //输出比较通道初始化
    RCC_APB1PeriphClockCmd(OUTPUT_PWM1_TIM_CLK,ENABLE);
    RCC_APB2PeriphClockCmd(OUTPUT_PWM1_GPIO_CLK,ENABLE);
    GPIO_InitStructure.GPIO_Pin = OUTPUT_PWM1_PIN;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(OUTPUT_PWM1_PORT,&GPIO_InitStructure);
    
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;            //时钟分频因子
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;        //计数器技术模式,向上计数
    TIM_TimeBaseStructure.TIM_Period = 500-1;                    
    TIM_TimeBaseStructure.TIM_Prescaler = 720-1;
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;                //重复计数器的值
    
    TIM_TimeBaseInit(OUTPUT_PWM1_TIM,&TIM_TimeBaseStructure);
    
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;                //PWM1模式
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;    //输出使能
    TIM_OCInitStructure.TIM_Pulse = 0;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;        //输出通道电平极性配置
    //输出比较通道
    TIM_OC1Init(OUTPUT_PWM1_TIM,&TIM_OCInitStructure);
    TIM_OC1PreloadConfig(OUTPUT_PWM1_TIM,TIM_OCPreload_Enable);
    TIM_ARRPreloadConfig(OUTPUT_PWM1_TIM,ENABLE);
    TIM_Cmd(OUTPUT_PWM1_TIM,ENABLE);                                //使能计数器
    
}
void Tim3Pwm1(u32 Duty)
{
    TIM_SetCompare1(OUTPUT_PWM1_TIM,Duty);
}

pwm.h

代码语言:javascript复制
#ifndef _BSP_PWM_H_
#define _BSP_PWM_H_

#include     "stm32f10x.h"

//PWM1
#define    OUTPUT_PWM1_TIM_CLK                  RCC_APB1Periph_TIM3
#define    OUTPUT_PWM1_GPIO_CLK                 RCC_APB2Periph_GPIOA    
#define    OUTPUT_PWM1_PIN                      GPIO_Pin_6
#define    OUTPUT_PWM1_PORT                     GPIOA
#define    OUTPUT_PWM1_TIM                      TIM3


void Tim3Pwm1Init(void);

//设置占空比
void Tim3Pwm1(u32 Duty);


#endif

0 人点赞