实验的STM32型号:
STM32F103C8T6 48引脚
涉及到的知识:
RCC,GPIO,TIMER,PWM 设置
*RCC需打开外部时钟
*GPIO查表得知 PA3 默认复用引脚 TIM2_CH4
*TIMER使用默认的TIM2_CH4
*PWM的控制使用了动态的占空比来达到呼吸效果
下面给出代码:
#include "stm32f10x.h"
void RCC_cfg(void);
void GPIO_cfg(void);
void TIMER_cfg(void);
void PWM_cfg(void);
int led_fx=1;
int led_dt=0;
void delay_ms(u16 time)
{
u16 i=0;
while(time--)
{
i=12000;
while(i--) ;
}
}
int main(void)
{
RCC_cfg();
GPIO_cfg();
TIMER_cfg();
PWM_cfg();
//使能TIM2计时器,开始输出PWM
TIM_Cmd(TIM2, ENABLE);
while(1)
{
delay_ms(5);
if(led_fx==1)
{
led_dt++;
}
else
{
led_dt--;
}
if(led_dt>500) led_fx=0;
if(led_dt==0) led_fx=1;
TIM_SetCompare4(TIM2,led_dt);
}
}
void RCC_cfg(void)
{
//定义错误状态变量
ErrorStatus HSEStartUpStatus;
//将RCC寄存器重新设置为默认值
RCC_DeInit();
//打开外部高速时钟晶振
RCC_HSEConfig(RCC_HSE_ON);
//等待外部高速时钟晶振工作
HSEStartUpStatus = RCC_WaitForHSEStartUp();
if(HSEStartUpStatus == SUCCESS)
{
//设置AHB时钟(HCLK)为系统时钟
RCC_HCLKConfig(RCC_SYSCLK_Div1);
//设置高速AHB时钟(APB2)为HCLK时钟
RCC_PCLK2Config(RCC_HCLK_Div1);
//设置低速AHB时钟(APB1)为HCLK的2分频
RCC_PCLK1Config(RCC_HCLK_Div2);
//设置FLASH代码延时
FLASH_SetLatency(FLASH_Latency_2);
//使能预取指缓存
FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
//设置PLL时钟,为HSE的9倍频 8MHz * 9 = 72MHz
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
//使能PLL
RCC_PLLCmd(ENABLE);
//等待PLL准备就绪
while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
//设置PLL为系统时钟源
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
//判断PLL是否是系统时钟
while(RCC_GetSYSCLKSource() != 0x08);
}
//开启TIM2的时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//开启GPIOB的时钟和复用功能
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,ENABLE);
}
void GPIO_cfg(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
// GPIO_PinRemapConfig(GPIO_PartialRemap1_TIM2, ENABLE); //映射引脚,默认PA3 ->TIM2_CH4因此不用映射
//选择引脚3
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
//输出频率最大50MHz
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//复用推挽输出
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
//PA
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
void TIMER_cfg(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//重新将Timer设置为缺省值
TIM_DeInit(TIM2);
//采用内部时钟给TIM2提供时钟源
TIM_InternalClockConfig(TIM2);
//预分频系数为0
TIM_TimeBaseStructure.TIM_Prescaler = 0;
//设置计数溢出大小
TIM_TimeBaseStructure.TIM_Period = 500;
//设置计数器模式为向上计数模式(+1)
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
//设置时钟分割
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//将配置应用到TIM2中
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);
}
void PWM_cfg(void)
{
TIM_OCInitTypeDef TimOCInitStructure;
//设置缺省值
TIM_OCStructInit(&TimOCInitStructure);
//PWM模式1输出
TimOCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
//设置占空比 (Led亮度)
TimOCInitStructure.TIM_Pulse = 0;
//TIM输出比较极性高
TimOCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
//使能输出状态
TimOCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
//TIM2的CH4输出
TIM_OC4Init(TIM2, &TimOCInitStructure);
//设置TIM2的PWM输出为使能
TIM_CtrlPWMOutputs(TIM2,ENABLE);
}