/*--------------------------------------------------------------------------------------
*  @file     TimerSetup.c
*  @author   ZhangJing
*  @version  base on stm32f0x   
*  @date     2015.09.11
*  @brief    定时器驱动
---------------------------------------------------------------------------------------*/
#include "stm32f10x_rcc.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_tim.h"
#include "TypeDefine.h"
#include "TimerSetup.h"

/*********************************************************************************
*  Function:	MotorPWMInit			                                                           
*  Object:		电机PWM初始化
*  输入:			无
*  输出:			无	                                     
*  备注:			用TIM1做PWM，控制电机转速              
**********************************************************************************/
void MotorPWMInit( void )
{
	TIM_OCInitTypeDef TIM_OCInitStructure;
	TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;

	TIM_DeInit(TIM1);

	/* TIM1模块初始化 */
	/* TIM1基本计数器设置（设置PWM频率） */
	/* 频率 = TIM1_CLK/(ARR+1) */
	TIM_TimeBaseStructure.TIM_Period = 1000 - 1; 					   
	TIM_TimeBaseStructure.TIM_Prescaler = 72 - 1;                       
	TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;    
	TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; 
	TIM_TimeBaseStructure.TIM_RepetitionCounter = 0;
	TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);	

	/* 启动ARR的影子寄存器（直到产生更新事件才更改设置） */
	TIM_ARRPreloadConfig(TIM1, ENABLE);

	//PWM模式设置 与通道设置TIM1_CH1（设置1通道占空比）
	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;	             
	TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
	TIM_OCInitStructure.TIM_OutputNState = TIM_OutputNState_Enable;
	TIM_OCInitStructure.TIM_Pulse = 0;					      				 //当计数器到达127时,电平发送跳变
	TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;	   //当计数器<127时,PWM为高电平
	TIM_OCInitStructure.TIM_OCNPolarity = TIM_OCNPolarity_Low;  //当计数器<127时,PWM为高电平
	TIM_OCInitStructure.TIM_OCIdleState  = TIM_OCIdleState_Reset;         //???????1
	TIM_OCInitStructure.TIM_OCNIdleState = TIM_OCIdleState_Reset;   //?????????0       
	TIM_OC1Init(TIM1, &TIM_OCInitStructure);

	//开启TIM1				 
	TIM_Cmd(TIM1, ENABLE);
	TIM_CtrlPWMOutputs(TIM1, ENABLE);  
	TIM_CCxNCmd(TIM1, TIM_Channel_1, TIM_CCxN_Enable);//Disable
}
