30 TIM_OC1PreloadConfig(TIM4,TIM_OCPreload_Disable); //改变点空比后,立即产生效应

31

32 TIM_OCInitStructure.TIM_Pulse=PWM_R; //左轮PWM的占空比

33 TIM_OC2Init(TIM4,&TIM_OCInitStructure); //PWM_R初始化

34 TIM_OC2PreloadConfig(TIM4,TIM_OCPreload_Disable); //改变点空比后,立即产生效应

35

36 //使能定时器4

37 TIM_Cmd(TIM4,ENABLE);

38 TIM_CtrlPWMOutputs(TIM4,ENABLE);

程序第一步:设置GPIO,略(输出PWM的管脚用Mode_AF_PP即可)

程序第二步:设置定时器,(保证产生两路PWM即可,我用的是TIM4)

void TIM4_Configuration(void)

{

TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;

TIM_OCInitTypeDef TIM_OCInitStructure;

//时间基初始化

TIM_TimeBaseInitStructure.TIM_Period=144; //18K/144=125Hz,这个是电机PWM的频率

TIM_TimeBaseInitStructure.TIM_Prescaler=4000; //72000000/4000=18K

TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;

TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up;

TIM_TimeBaseInitStructure.TIM_RepetitionCounter=0x0000;

TIM_TimeBaseInit(TIM4,&TIM_TimeBaseInitStructure);

//输出比较模式设置,用于4路PWM输出

TIM_OCInitStructure.TIM_OCMode=TIM_OCMode_PWM2; //输出PWM

TIM_OCInitStructure.TIM_OutputState=TIM_OutputState_Enable; //使能正向通道

TIM_OCInitStructure.TIM_OutputNState=TIM_OutputState_Disable; //失能反向通道

TIM_OCInitStructure.TIM_Pulse=PWM_L; //左轮DIR的占空比

TIM_OCInitStructure.TIM_OCPolarity=TIM_OCPolarity_Low; //输出极性为低电平

TIM_OCInitStructure.TIM_OCNPolarity=TIM_OCPolarity_High;//互补输出极性为高电平

TIM_OCInitStructure.TIM_OCIdleState=TIM_OCIdleState_Set;

TIM_OCInitStructure.TIM_OCNIdleState=TIM_OCNIdleState_Reset;

TIM_OC1Init(TIM4,&TIM_OCInitStructure); //PWM_L初始化

TIM_OC1PreloadConfig(TIM4,TIM_OCPreload_Disable); //改变点空比后,立即产生效应

TIM_OCInitStructure.TIM_Pulse=PWM_R; //左轮PWM的占空比

TIM_OC2Init(TIM4,&TIM_OCInitStructure); //PWM_R初始化

TIM_OC2PreloadConfig(TIM4,TIM_OCPreload_Disable); //改变点空比后,立即产生效应

//使能定时器4

TIM_Cmd(TIM4,ENABLE);

TIM_CtrlPWMOutputs(TIM4,ENABLE);

1 程序第三步:

2

3 在SysTick中断中,读取两个轮子的速度(具体的方法是:每0.1秒读一次,并以此人作为速度的依据),并比较,如果以右轮为基准,则调整左轮的PWM占空比。涉及到关键语句是:TIM_SetCompare1();

4

5 u16 COUN1=0;

6 u16 COUN2=0;

7

8 volatile u16 Dist_L=0; //左轮行程脉冲数

9 volatile u16 Dist_R=0; //右轮行程脉冲数

10 void SysTick_Handler(void)

11 {

12