参考程序
#include "stm32f10x.h"//定时器4主模式//PWM输出void TIM4_config(u32 Cycle){ GPIO_InitTypeDef GPIO_InitStructure; TIM_TimebaseInitTypeDef TIM_TimebaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4 ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; //TIM2_CH2 PB7 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB &GPIO_InitStructure); TIM_TimebaseStructure.TIM_Period = Cycle-1; TIM_TimebaseStructure.TIM_Prescaler =71; //设置用来作为TIMx时钟频率除数的预分频值 TIM_TimebaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割:TDTS= Tck_tim TIM_TimebaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式 TIM_TimebaseInit(TIM4 &TIM_TimebaseStructure); TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式1 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能 TIM_OCInitStructure.TIM_Pulse = Cycle/2-1; //设置待装入捕获寄存器的脉冲值 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; //输出极性 TIM_OC2Init(TIM4 &TIM_OCInitStructure); TIM_SelectMasterSlaveMode(TIM4 TIM_MasterSlaveMode_Enable); TIM_SelectOutputTrigger(TIM4 TIM_TRGOSource_Update); TIM_OC2PreloadConfig(TIM4 TIM_OCPreload_Enable); TIM_ARRPreloadConfig(TIM4 ENABLE); }/@@***定时器3从模式***/void TIM3_config(u32 PulseNum){ TIM_TimebaseInitTypeDef TIM_TimebaseStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3 ENABLE); TIM_TimebaseStructure.TIM_Period = PulseNum-1; TIM_TimebaseStructure.TIM_Prescaler =0; TIM_TimebaseStructure.TIM_ClockDivision = 0; TIM_TimebaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimebaseInit(TIM3 &TIM_TimebaseStructure); TIM_SelectInputTrigger(TIM3 TIM_TS_ITR3); //TIM_InternalClockConfig(TIM3); TIM3->SMCR|=0x07; //设置从模式寄存器 //TIM_ARRPreloadConfig(TIM3 ENABLE); TIM_ITConfig(TIM3TIM_IT_UpdateDISABLE); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_3); NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure);}void Pulse_output(u32 Cycleu32 PulseNum){ TIM3_config(PulseNum); TIM_Cmd(TIM3 ENABLE); TIM_ClearITPendingBit(TIM3TIM_IT_Update); TIM_ITConfig(TIM3TIM_IT_UpdateENABLE); TIM4_config(Cycle); TIM_Cmd(TIM4 ENABLE);}