蓝桥杯嵌入式学习————PWM配置及端口重映射

PWM配置及端口重映射

为了看出效果,这里PWM使用的是TIM3的3,4通道作为pwm输出, 因为led灯的引脚连接在PC8~PC15上,所以只有使用PC9和PC10的端口重映射(Remap)。
在这里插入图片描述
下面是端口重映射配置程序

void PWM_IO_Config(void)
{
    GPIO_InitTypeDef  GPIO_InitStructure;
  
	//RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); 在TIM_config中配置了,此处就不写了
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC|RCC_APB2Periph_AFIO, ENABLE);   //开启C端口和复用时钟
	
	GPIO_PinRemapConfig(GPIO_FullRemap_TIM3,ENABLE);   //TIM3重映射使能
	
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;   //复用推挽输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
 }

然后对定时器进行配置,使其能够产生相应的PWM波(ps:这里 led 低电平亮

PWM模式1- 在向上计数时,一旦TIMx_CNT

TIM_TimeBaseStructure.TIM_Period = 1000-1; //自动重装载值
TIM_TimeBaseStructure.TIM_Prescaler = 71; //预分频值
所以这里PWM的频率为: 72Mhz / (71+1) / (1000-1+1) = 1 Khz
占空比=TIM_Pulse/TIM_Period;

void TIM_Config(uint16_t Channel3Pulse, uint16_t Channel4Pulse)
{
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;
	
	/* TIM3 clock enable */
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);		
	
	/* Time base configuration  定时器设置 */
	TIM_TimeBaseStructure.TIM_Period = 1000-1;  //1KHz   //自动重装载值,则pwm周期为TIM时钟周期/TIM_Period  
	TIM_TimeBaseStructure.TIM_Prescaler = 71;    //预分频值
	TIM_TimeBaseStructure.TIM_ClockDivision = 0;
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
	//TIM3预分频设置:1MHZ,APB1分频系数为2 输出到TIM3时钟为36MHzx2 = 72MHz  	

	/* Channel 3 and 4 Configuration in PWM mode    通道设置*/
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;   //PWM模式1
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = Channel3Pulse;    //设置通道3脉冲值,即计数周期内有效电平的时间(脉冲次数),可得出占空比: TIM_Pulse/TIM_Period
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;  //有效电平为低电平
	TIM_OC3Init(TIM3, &TIM_OCInitStructure);

	TIM_OCInitStructure.TIM_Pulse = Channel4Pulse;     //设置通道4脉冲值
	TIM_OC4Init(TIM3, &TIM_OCInitStructure);

	//使能TIM3定时计数器
	TIM_Cmd(TIM3, ENABLE);
	//使能TIM3 pwm输出模式
	TIM_CtrlPWMOutputs(TIM3, ENABLE);
}

使用系统滴答时钟作了一个LED呼吸灯

extern void TIM_Config(uint16_t Channel3Pulse, uint16_t Channel4Pulse);
u16 led_time=0;
u16 led_flag=0;
void SysTick_Handler(void)
{
	TimingDelay--;
	
	
	if(led_flag==1) 	led_time--;
	if(led_flag==0)  	led_time++;

	TIM_Config(led_time,0);
	if(led_time==998) {led_flag=1;}
	if(led_time==0){led_flag=0;}	
}

OK

你可能感兴趣的:(蓝桥杯嵌入式)