#include "at32f403a_407.h"
#include "wdt.h"


//
void wdt_init(void)
{
    gpio_init_type gpio_initstructure;

// -----------------------------------------------------------------------------
// GPIO        
    
    crm_periph_clock_enable(CRM_GPIOE_PERIPH_CLOCK, TRUE);

    gpio_initstructure.gpio_out_type       = GPIO_OUTPUT_PUSH_PULL;  
    gpio_initstructure.gpio_pull           = GPIO_PULL_NONE;  
    gpio_initstructure.gpio_mode           = GPIO_MODE_OUTPUT;  
    gpio_initstructure.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
    gpio_initstructure.gpio_pins           = GPIO_PINS_6;
    gpio_init(GPIOE, &gpio_initstructure); 

// -----------------------------------------------------------------------------
// TIM    
    
    crm_clocks_freq_type crm_clocks_freq_struct = {0};
    
    crm_periph_clock_enable(CRM_TMR13_PERIPH_CLOCK, TRUE);
    
    crm_clocks_freq_get(&crm_clocks_freq_struct);
    tmr_base_init(TMR13, 999, (crm_clocks_freq_struct.ahb_freq / 10000) - 1);
    tmr_cnt_dir_set(TMR13, TMR_COUNT_UP);
        
    tmr_flag_clear(TMR13, TMR_OVF_FLAG);
       
    nvic_irq_enable(TMR8_OVF_TMR13_IRQn, 2, 0);
    
    tmr_counter_enable(TMR13, TRUE);
    
    tmr_interrupt_enable(TMR13, TMR_OVF_INT, TRUE);
}


void TMR8_OVF_TMR13_IRQHandler(void)
{
    if (tmr_flag_get(TMR13, TMR_OVF_FLAG) != RESET)
    {
        tmr_flag_clear(TMR13, TMR_OVF_FLAG);
       
        GPIOE->odt ^= GPIO_PINS_6;
    }
}


// Дергаем пином (сброс внешнего WDT)
void wdt_reset(void)
{
    GPIOE->odt ^= GPIO_PINS_6;
}
