(蓝桥杯嵌入式)TIM2输出两路不同频率不同占空比的PWM波

目录

1.pwm_out.c

2.pwm_out.h


1.pwm_out.c

初始化及翻转输出中断服务函数


#include "pwm_out.h"

u16 capture=0;
u16 CH2_Flag=0,CH3_Flag=0;
u16 CCR2=5000,CCR3=4000;
float CH2_Duty=0.1,CH3_Duty=0.7;

void TIM2_PWM_OUT(void)
{
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
  TIM_OCInitTypeDef  TIM_OCInitStructure;
	GPIO_InitTypeDef GPIO_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;
	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
	
	TIM_TimeBaseStructure.TIM_Period = 65535;
  TIM_TimeBaseStructure.TIM_Prescaler = 71;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

  TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle;
  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_Pulse = CCR2;
  TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;
  TIM_OC2Init(TIM2, &TIM_OCInitStructure);
  TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Disable);

  TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
  TIM_OCInitStructure.TIM_Pulse = CCR3;
  TIM_OC3Init(TIM2, &TIM_OCInitStructure);
  TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Disable);
	
	
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);
	
	TIM_ITConfig(TIM2,TIM_IT_CC2 | TIM_IT_CC3, ENABLE);
	TIM_Cmd(TIM2, ENABLE);
}

//TIM2中断服务函数
void TIM2_IRQHandler(void)
{
  if (TIM_GetITStatus(TIM2, TIM_IT_CC2) != RESET)
  {
		TIM_ClearITPendingBit(TIM2, TIM_IT_CC2 );
		 capture = TIM_GetCapture2(TIM2);
		
		if(CH2_Flag==1)
		{
			 CH2_Flag=0;
       TIM_SetCompare2(TIM2,capture + CCR2*CH2_Duty);
		}
		else
		{
			 CH2_Flag=1;
       TIM_SetCompare2(TIM2,capture + CCR2*(1-CH2_Duty));
		}
  }
	
  if (TIM_GetITStatus(TIM2, TIM_IT_CC3) != RESET)
  {
		TIM_ClearITPendingBit(TIM2, TIM_IT_CC3 );
		 capture = TIM_GetCapture3(TIM2);
		
		if(CH3_Flag==1)
		{
			 CH3_Flag=0;
       TIM_SetCompare3(TIM2,capture + CCR3*CH3_Duty);
		}
		else
		{
			CH3_Flag=1;
      TIM_SetCompare3(TIM2,capture + CCR3*(1-CH3_Duty));
		}
  }
	
	
}

2.pwm_out.h


#ifndef __PWM_OUT_H
#define __PWM_OUT_H

#include "stm32f10x.h"

void TIM2_PWM_OUT(void);



#endif /* __PWM_OUT_H */

你可能感兴趣的:(嵌入式学习笔记,蓝桥杯,stm32,c语言)