/********************************* (C) РОТЕК ***********************************
 * @module  wdg
 * @file    wdg.c
 * @version 1.0.0
 * @date    XX.XX.XXXX
 * $brief   External watchdog (pin PE11)
 *******************************************************************************
 * @history     Version  Author         Comment
 * XX.XX.XXXX   1.0.0    Telenkov D.A.  First release.
 *******************************************************************************
 */

#include "stm32f4xx.h"  
#include "wdg.h"

/**
  * @brief  
  * @retval 
  */
void WDG_Init(void)
{
  
  GPIO_InitTypeDef GPIO_InitStructure;
  NVIC_InitTypeDef          NVIC_InitStructure;
  TIM_TimeBaseInitTypeDef   TIM_TimeBaseStructure;
  
  RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM13, ENABLE);
  
  GPIO_InitStructure.GPIO_Pin = WDT_PIN;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIOE, &GPIO_InitStructure);
  
  NVIC_InitStructure.NVIC_IRQChannel = TIM8_UP_TIM13_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x6;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  NVIC_SetPriority(TIM8_UP_TIM13_IRQn, 2);
  
  /* APB1 Timer clock is 60Mhz, configure timer clock to 10khz (1 update event per 100 us) */
  TIM_TimeBaseStructure.TIM_Prescaler = 6000 - 1;
  /* Configure timer period to 100ms */
  TIM_TimeBaseStructure.TIM_Period = 1000;
  TIM_TimeBaseStructure.TIM_ClockDivision = 0;
  TIM_TimeBaseStructure.TIM_CounterMode	= TIM_CounterMode_Up;
  TIM_TimeBaseInit(TIM13, &TIM_TimeBaseStructure);
  
  TIM_Cmd(TIM13, ENABLE);
  TIM_ITConfig(TIM13, TIM_IT_Update, ENABLE);
  
}

/**
  * @brief  Дергаем пином (сброс внешнего WDT)
  * @retval 
  */
void TIM8_UP_TIM13_IRQHandler(void)
{
  TIM_ClearITPendingBit(TIM13, TIM_IT_Update);
  GPIOE->ODR ^= WDT_PIN;
}

/**
  * @brief  Дергаем пином (сброс внешнего WDT)
  */
void WDT_Reset(void)
{
  GPIOE->ODR ^= WDT_PIN;
}


/********************************* (C) РОТЕК **********************************/
