首页 > 其他分享 >STM32用PWM波控制呼吸灯代码

STM32用PWM波控制呼吸灯代码

时间:2022-12-16 10:23:22浏览次数:43  
标签:TIM3 代码 OCInitStruct STM32 TIM TimeBaseInitStruct GPIO PWM

pwm.c

#include "pwm.h"

//TIM3-CH3
//PB0
void PWM_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStruct;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
	TIM_OCInitTypeDef TIM_OCInitStruct;
	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
	
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_0;
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIO_InitStruct);
	
	TIM_TimeBaseInitStruct.TIM_CounterMode=TIM_CounterMode_Up;
	TIM_TimeBaseInitStruct.TIM_Period=9999;
	TIM_TimeBaseInitStruct.TIM_Prescaler=71;
	TIM_TimeBaseInitStruct.TIM_ClockDivision=0;
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStruct);
	
	TIM_OCInitStruct.TIM_OCPolarity=TIM_OCPolarity_Low;
	TIM_OCInitStruct.TIM_OCMode=TIM_OCMode_PWM1;
	TIM_OCInitStruct.TIM_OutputState=TIM_OutputState_Enable;
	TIM_OCInitStruct.TIM_Pulse=4999;
	TIM_OC3Init(TIM3, &TIM_OCInitStruct);
	
	TIM_Cmd(TIM3, ENABLE);
}

pwm.h

#ifndef __PWM_H
#define __PWM_H

#include "stm32f10x.h"

void PWM_Config(void);

#endif

main.c

#include "stm32f10x.h"
#include "pwm.h"
#include "delay.h"

uint16_t a = 0;

int main(void)
{
	PWM_Config();
	delay_init();
	
	while(1)
	{
		for(a = 4999; a > 0; a--)
		{
			TIM_SetCompare3(TIM3, a);
			delay_us(200);
		}
		for(a = 0; a < 5000; a++)
		{
			TIM_SetCompare3(TIM3, a);
			delay_us(200);
		}
	}
}
  • 用了重映射则需要
    • 开启复用时钟
    • 使能GPIO重映射GPIO_PinRemapConfig
  • GPIO输出模式一定是复用推挽

标签:TIM3,代码,OCInitStruct,STM32,TIM,TimeBaseInitStruct,GPIO,PWM
From: https://www.cnblogs.com/Sound-Sleep/p/16986625.html

相关文章