


#include "board.h"
#include "stm32f10x.h"



static int init(timer_def *t){
  static int inited=0;
  if(inited!=0) return 0;
  inited=1;
	TIM_TimeBaseInitTypeDef timer;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE );
	NVIC_DisableIRQ(TIM4_IRQn);
	TIM_DeInit(TIM4);							
	timer.TIM_Period           = 10000-1;		//1s
	timer.TIM_Prescaler        = 7200-1;//1K;	//预分频72MHz主频，分频后时钟周期0.1ms
	timer.TIM_ClockDivision    = TIM_CKD_DIV1;  //分频
	timer.TIM_CounterMode      = TIM_CounterMode_Up;  //向上计数
	timer.TIM_RepetitionCounter=0;
	TIM_TimeBaseInit(TIM4,&timer);
	TIM_SetCounter(TIM4,0);
	TIM_ARRPreloadConfig(TIM4, ENABLE);
  TIM_SelectOutputTrigger(TIM4,TIM_TRGOSource_Update);
	TIM_Cmd(TIM4, ENABLE);

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5, ENABLE );
	NVIC_DisableIRQ(TIM5_IRQn);
	TIM_DeInit(TIM5);							
	timer.TIM_Period           = 0xffff;// 
	timer.TIM_Prescaler        = 0;//不分频
	timer.TIM_ClockDivision    = TIM_CKD_DIV1;
	timer.TIM_CounterMode      = TIM_CounterMode_Up;  //向上计数
	timer.TIM_RepetitionCounter=0;
	TIM_TimeBaseInit(TIM5,&timer);
	TIM_SetCounter(TIM5,0);
	TIM_ARRPreloadConfig(TIM5, ENABLE);
  TIM_ITRxExternalClockConfig(TIM5, TIM_TS_ITR2);
	TIM_Cmd(TIM5, ENABLE);


  return 0;
}

static int deinit(timer_def *t){
	TIM_DeInit(TIM4);							
	TIM_DeInit(TIM5);							
  return 0;
}

static uint32_t read(timer_def *t)
{
  uint32_t ms;
  ms=TIM_GetCounter(TIM4)/10+TIM_GetCounter(TIM5)*1000;
  return ms;
}
static int write(timer_def *t,const uint32_t value)
{
  TIM_Cmd(TIM4,DISABLE);
  TIM_SetCounter(TIM4,(value%1000)*10);
  TIM_SetCounter(TIM5,value/1000);
  TIM_Cmd(TIM4,ENABLE);
  return 0;
}





timer_init_export(timer,init,deinit,read,write,0);

