/*******************************************************************************
  * @filename          : TIM.h
  * @brief             : 定时器的初始化配置
	* @author            : zhanli
	* @date              : 2024/08/21
  *****************************************************************************/
/* Includes ------------------------------------------------------------------*/
#include "tim.h"


TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim4;

/**
  * @brief   : 定时器3初始化是用于定时100ms发送UWB的定位数据
  * @author  : zhanli
  * @date    : 2024/08/22
  * @retval  : None
  */
void TIM3_Init(void)
{
  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  htim3.Instance               = TIM3;
  htim3.Init.Prescaler         = 7200-1;
  htim3.Init.CounterMode       = TIM_COUNTERMODE_UP;
  htim3.Init.Period            = 100-1;
  htim3.Init.ClockDivision     = TIM_CLOCKDIVISION_DIV1;
  htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
/**
  * @brief   : 定时器4初始化, 用于支持us级别的延时(DW1000需要)
  * @author  : zhanli
  * @date    : 2024/08/22
  * @retval  : None
  */
void TIM4_Init(void)
{
  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  htim4.Instance           = TIM4;
  htim4.Init.Prescaler     = 72-1;
  htim4.Init.CounterMode   = TIM_COUNTERMODE_UP;
  htim4.Init.Period        = 1;
  htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }

}

/**
  * @brief   : 定时器4初始化, 用于支持us级别的延时(DW1000需要)
  * @param     us : 延时的微秒数 
  * @author  : zhanli
  * @date    : 2024/08/22
  * @retval  : None
  */
void delay_us(uint16_t us)
{
    uint16_t differ=0xffff-us-5;

    HAL_TIM_Base_Start(&htim4);
    __HAL_TIM_SetCounter(&htim4, differ);
    while(differ < 0xffff-5)
    {
        differ = __HAL_TIM_GetCounter(&htim4);
    }
    HAL_TIM_Base_Stop(&htim4);

}
