通用定时器PWM概述
?
?
?
?
?
?
?
常用寄存器和库函数配置
?
?
?
手把手写PWM输出实验
?
#ifndef __PWM_H
#define __PWM_H
#include "sys.h"
void TIM14_PWM_Init(u32 arr, u32 crr);
#endif
#include "stm32f4xx.h"
#include "pwm.h"
void TIM14_PWM_Init(u32 arr, u32 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
// 初始化时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14,ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF,ENABLE);
// 初始化IO口 复用功能输出
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIOF,&GPIO_InitStructure);
// PF9复用映射到TIM14
GPIO_PinAFConfig(GPIOF,GPIO_PinSource9,GPIO_AF_TIM14);
// 初始化定时器
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_Period = arr;
TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
TIM_TimeBaseInit(TIM14,&TIM_TimeBaseInitStructure);
// 初始化输入比较参数
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OC1Init(TIM14,&TIM_OCInitStructure);
// 使能预装载寄存器
TIM_OC1PreloadConfig(TIM14,TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM14,ENABLE);
// 使能定时器
TIM_Cmd(TIM14,ENABLE);
}
#include "stm32f4xx.h"
#include "led.h"
#include "delay.h"
#include "pwm.h"
int main(void)
{
u16 led0pwmval = 0;
u8 dir = 1;
delay_init(168);
LED_Init();
//84M/84=1MHz的计数频率,重装载值500,所以PWM频率为1M/500=2kHz
TIM14_PWM_Init(500-1,84-1);
while(1)
{
delay_ms(10);
if(dir)led0pwmval++; // dir==1 led0pwmval递增
else led0pwmval--; // dir==1 led0pwmval递减
if(led0pwmval > 300)dir = 0; //led0pwmval达到300,递减
if(led0pwmval== 0)dir=1; //led0pwmval到0,递增
//修改比较值,占空比
TIM_SetCompare1(TIM14,led0pwmval);
}
}
|