第一章 定时器PWM功能介绍
STM32F407的定时器的 TIM6 和 TIM7 是普通定时器,除此之外,其他的定时器都可以用来产生 PWM 输出。其中高级定时器 TIM1 和 TIM8 可以同时产生多达 7 路的 PWM 输出。而通用定时器也能同时产生多达4路的PWM输出;在开发四轴无人机、机器人等需要控制大量电机的产品里运用起来非常方便。
第二章 PWM波形输出通道介绍
定时器3的硬件PWM通道:PA6 PA7 PB0 PB1
下面截图是介绍定时器3通道的复用IO口模式配置方式
第三章 配置PWM波形输出代码示例
3.1 在工程中增加pwm.c文件,写入以下代码
#include "pwm.h"
/*
函数功能:定时器3-PWM波形输出配置
硬件PWM通道:PA6 PA7 PB0 PB1
功能说明:配置定时器3的通道1输出PWM波形
*/
void Timer3_PWM_Init(u16 psc,u16 arr)
{
/*1. 开时钟*/
RCC->APB1ENR|=1<<1; //开启定时器3的时钟
RCC->APB1RSTR|=1<<1; //开启复位时钟
RCC->APB1RSTR&=~(1<<1);//关闭
/*2. 配置定时器的核心寄存器*/
TIM3->PSC=psc-1; //预分频
/*计数器的时钟频率CK_CNT等于fCK_PSC/(PSC[15:0]+1)*/
TIM3->ARR=arr; //重装载寄存器
/*3. 配置PWM波形相关寄存器*/
TIM3->CCMR1&=~(0x3<<0);
TIM3->CCMR1|=0x0<<0; //CC1通道被配置为输出
TIM3->CCMR1&=~(0x7<<4);
//TIM3->CCMR1|=0x6<<4; //模式1
TIM3->CCMR1|=0x7<<4; //模式2
TIM3->CCER|=1<<0; //OC1信号输出到对应的输出引脚
TIM3->CCR1=arr/2; //占空比 50%
/*4. 配置PWM波形输出的GPIO口*/
RCC->AHB1ENR|=1<<0; //使能PORTA时钟
GPIOA->MODER&=~(0x3<<6*2); //清除模式
GPIOA->MODER|=0x2<<6*2; //配置复用功能模式
GPIOA->OTYPER&=~(0x1<<6); //0表示推挽输出
GPIOA->OSPEEDR&=~(0x3<<6*2); //清除之前配置
GPIOA->OSPEEDR|=0x2<<6*2; //50MHZ输出速度
GPIOA->AFR[0]&=~(0xF<<4*6); //清除PA6配置
GPIOA->AFR[0]|=0x2<<4*6; //配置PA6复用功能模式为定时器3的通道1
/*5. 开启定时器*/
TIM3->CR1|=1<<0;
}
3.2 Main.c文件代码示例
int main(void)
{
LED_Init();
KEY_Init();
USART1_Init(84,115200);
KEY_EXTI_Init();
Timer3_PWM_Init(84,1000); //分频84,得到频率是1MHZ
TIM3->CCR1=500; //占空比是50%
while(1)
{
}
}
相关文章









