STM32PWM实现呼吸灯-库函数

最让我头大的是初始化函数的各个参数的设置,在这里给出pwm_init的模板

pwm.h:

#include "pwm.h"

void TIM14_PWM_init(u32 arr, u32 psc) //arr为定时器的自动装载值(决定周期),cnt达到arr时io要置0,psc为预分频系数
{
    GPIO_InitTypeDef GPIO_InitStructure;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
    TIM_OCInitTypeDef TIM_OCInitStructure;

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14, ENABLE); //使能TIM14的时钟
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); //使能GPIOF的时钟

    //初始化IO口
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_PuPd_UP;
    GPIO_Init(GPIOF, &GPIO_InitStructure);

    //响应IO口复用映射到响应寄存器
    GPIO_PinAFConfig(GPIOF, GPIO_PinSource9, GPIO_AF_TIM14);

    //初始化定时器
    TIM_TimeBaseInitStructure.TIM_Prescaler = psc; //定时器分频
    TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; //计数模式(向上计数模式)
    TIM_TimeBaseInitStructure.TIM_Period = arr; //自动重装载值
    TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; 
    TIM_TimeBaseInit(TIM14, &TIM_TimeBaseInitStructure); //初始化定时器14

//pwm初始化核心代码-----------------------------------------------------------------------------------------------
    //初始化输出比较参数
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM模式1
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性(极性的作用:有效的电平是高还是低)
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
    TIM_OC1Init(TIM14, &TIM_OCInitStructure); //初始化外设TIM3 OC2

    TIM_OC1PreloadConfig(TIM14, TIM_OCPreload_Enable);//使能TIM14在CCR1上的预装载寄存器
    TIM_ARRPreloadConfig(TIM14, ENABLE); //ARPE使能
//---------------------------------------------------------------------------------------------------------------

    TIM_Cmd(TIM14, ENABLE); //使能定时器
}

然后是mian中实现呼吸灯的算法(这里的u16型变量坑了我一把,无符号啊,不能是负数,555!)

main.c:

#include "led.h"
#include "sys.h"
#include "usart.h"
#include "delay.h"
#include "pwm.h"

int main(void)
{
	u16 i;
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	delay_init(168);
	uart_init(115200);
	TIM14_PWM_init(500-1, 84-1);
	while (1) 
	{
		i = 0; //i置为0
		
		while (i <= 300) {
			delay_ms(10);
			TIM_SetCompare1(TIM14, i);
			i++;
		}
		
		i = 300; //i置为300
		
		while (i > 0) {
			delay_ms(10);
			TIM_SetCompare1(TIM14, i);
			i--;
		}
		
	}

}

 

你可能感兴趣的:(STM32基础实验)