STM32F1基本配置7.PWM输出配置

PWM输出配置代码

	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;

	//时钟使能
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
 	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA , ENABLE);  
	                                                                     	

    //TIM-CH1 PA8
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;  
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	
	TIM_TimeBaseStructure.TIM_Period = arr; //自动重装载值
	TIM_TimeBaseStructure.TIM_Prescaler =psc; //预分配因子
	TIM_TimeBaseStructure.TIM_ClockDivision = 0; //设置时钟分割
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//向上计数
	TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); //初始化

	//配置PWM
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //选择模式
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //输出比较
	TIM_OCInitStructure.TIM_Pulse = 0; //装入捕获比较寄存器值
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性高
	TIM_OC1Init(TIM1, &TIM_OCInitStructure);  //初始化

    TIM_CtrlPWMOutputs(TIM1,ENABLE);	//高级TIM1 - MOE寄存器位 输出使能	

	TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);  //CH1预装载使能	 
	
	TIM_ARRPreloadConfig(TIM1, ENABLE); //使能ARR预装载寄存器
	
	TIM_Cmd(TIM1, ENABLE);  //使能TIM1

重设比较寄存器值

	TIM_SetCompare1(TIM1,led0pwmval);	 

你可能感兴趣的:(STM32F1基本配置,C语言,STM32F1)