STM32F407 basic timer configuration output PWM square wave

Introduce the STM32F407 timer PWM waveform output configuration method. The waveform data is collected through logic analysis for visual display comparison.

【1】Timer PWM function introduction

The timers of STM32F4 except TIM6 and 7. Other timers can be used to generate PWM output. The advanced timers TIM1 and TIM8 can simultaneously generate up to seven PWM outputs. The general-purpose timer can also generate up to 4 PWM outputs at the same time!

img

img

img

【2】PWM waveform output channel introduction

img

img

img

Hardware PWM channel of Timer 3: PA6 PA7 PB0 PB1

The screenshot below is to introduce the configuration method of the multiplexed IO port mode of the timer 3 channel

img

img

【3】Configure PWM waveform output code example

Add the pwm.c file to the project and write the following code

#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;
}


Main.c file code example

#include "stm32f4xx.h" // Device header
#include "led.h"
#include "delay.h"
#include "key.h"
#include "usart.h"
#include "sys.h"
#include "exti.h"
#include "timer.h"
#include "pwm.h"

int main(void)
{
    
    
		LED_Init();
		KEY_Init();
		USART1_Init(84,115200);
		KEY_EXTI_Init();
		Timer3_PWM_Init(84,1000);
	  TIM3->CCR1=500;
	  while(1)
		{
    
    
			  
		}
}

img

Guess you like

Origin blog.csdn.net/xiaolong1126626497/article/details/131458501
Recommended