STM32PWM输出实现LED灯渐亮渐灭
扫描二维码
随时随地手机看文章
/*
*说明:
*PA0:KEY1;PA1:KEY2;
*PA2:LED1;PA3:LED2;
*PA9:USART1_TX;PA10:USART1_RX
*/
#include"stm32f10x.h"
#include"stm32f10x_rcc.h"
#include"stm32f10x_gpio.h"
#include"stm32f10x_tim.h"
#include"stm32f10x_pwr.h"
#include"stm32f10x_exti.h"
#include"system_stm32f10x.h"
#include"misc.h"
voidRCC_Configuration(void);
voidGPIO_Configuration(void);
voidTIM2_Configuration(void);
voiddelay_ms(u16time);
intmain()
{
u8led_fx=1;
u16led_dt=0;
RCC_Configuration();
GPIO_Configuration();
TIM2_Configuration();
while(1)
{
delay_ms(10);
if(led_fx==1)
{
led_dt++;
}else{
led_dt--;
}
if(led_dt>100)led_fx=0;//可以和初始值一样
if(led_dt==0)led_fx=1;
TIM_SetCompare3(TIM2,led_dt);//通道3没有重影像是PA2对应LED1
TIM_SetCompare4(TIM2,led_dt);//通道4没有重影像是PA3对应LED2
}
}
voidRCC_Configuration(void)
{
SystemInit();
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//GPIO_AFIODeInit();和下面相同效果,可以查看源码证明
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE);
}
voidGPIO_Configuration(void)
{
GPIO_InitTypeDefGPIO_InitStructure;
//GPIO_PinRemapConfig(GPIO_PartialRemap2_TIM2,ENABLE);//端口映射函数
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2|GPIO_Pin_3;//GPIO_Pin_3对应channel3,主函数改为:TIM_SetCompare3
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
voidTIM2_Configuration(void)
{
TIM_TimeBaseInitTypeDefTIM_TimeBaseStructure;
TIM_OCInitTypeDefTIM_OCInitStructure;
TIM_DeInit(TIM2);
TIM_InternalClockConfig(TIM2);
//定时器初始化
TIM_TimeBaseStructure.TIM_Period=100-1;//初始值是100,2MHz=2000KHz,2MHz/100=0.02MHz,所有周期T=1/0.02MHz=50us,示波器显示周期应该为50us
TIM_TimeBaseStructure.TIM_Prescaler=36-1;//36倍分频,72MHz/36=2MHz
TIM_TimeBaseStructure.TIM_ClockDivision=0;
TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up;
TIM_TimeBaseStructure.TIM_RepetitionCounter=0;
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);
//PWM初始化
TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse=50;//占空比值是50,所以占空比是:50/100=50%
TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low;
TIM_OC3Init(TIM2,&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_Pulse=20;
TIM_OC4Init(TIM2,&TIM_OCInitStructure);
//TIM_OC3PreloadConfig(TIM2,TIM_OCPreload_Enable);
//TIM_ARRPreloadConfig(TIM2,ENABLE);
TIM_Cmd(TIM2,ENABLE);
TIM_CtrlPWMOutputs(TIM2,ENABLE);
}
voiddelay_ms(u16time)
{
u16i=0;
while(time--)
{
i=12000;
while(i--);
}
}