基本原理
PWM相关物理量的求法
呼吸灯代码
#include "stm32f10x.h" // Device header
#include "Delay.h"TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_OCInitTypeDef TIM_OCInitStructuer;//结构体
GPIO_InitTypeDef GPIO_InitStructur;//定义变量结构体void GPIOA_Init(void){RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);GPIO_InitStructur.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_InitStructur.GPIO_Pin = GPIO_Pin_0; //GPIO_Pin_15;GPIO_InitStructur.GPIO_Speed = GPIO_Speed_50MHz;GPIO_Init(GPIOA, &GPIO_InitStructur);
}void PWM_Init(void){ //pwm波形配置TIM_OCStructInit(&TIM_OCInitStructuer);//给不需要配置的结构体成员赋予初始值TIM_OCInitStructuer.TIM_OCMode = TIM_OCMode_PWM1; //输出比较模式TIM_OCInitStructuer.TIM_OCPolarity = TIM_OCPolarity_High; //极性TIM_OCInitStructuer.TIM_OutputState = TIM_OutputState_Enable; //输出使能TIM_OCInitStructuer.TIM_Pulse = 0; //CCR,频率1kHZ,占空比50%的PWM波形TIM_OC1Init(TIM2, &TIM_OCInitStructuer);//配置GPIOA端口通道
}/*定时器定时中断代码*/void Timer_Init(void)//使用TM2定时器
{RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);GPIOA_Init();TIM_InternalClockConfig(TIM2);TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;TIM_TimeBaseInitStructure.TIM_Period = 100 - 1; //ARRTIM_TimeBaseInitStructure.TIM_Prescaler = 720 - 1; //PSCTIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);PWM_Init();TIM_Cmd(TIM2, ENABLE);//启动定时器
}/*CCR控制灯的亮度在运行过程中不断更改CCR的值来达到呼吸效果*/ //CCR[0~100]值越大灯越亮
void PWM_setcompare1(uint16_t compare){TIM_SetCompare1(TIM2, compare);
}uint8_t i;int main(void){Timer_Init();while(1){for(i = 0; i <= 100; i ++){PWM_setcompare1(i);Delay_ms(10);}for(i = 0; i <= 100; i ++){PWM_setcompare1(100 - i);Delay_ms(10);}}
}
注:TIM_OutputState 和 TIM_OutputNState不同
效果:
亮度会由暗变亮再变暗循环往复