/*
 * mcu_iwdg.h
 *
 *  Created on: 9/9/2021
 *      Author: alexrayne <alexraynepe196@gmail.com>
 * --------------------------------------------------------------------------------------------------------------------
 *  iwdg API, compat to STM HAL
 */

#ifndef BSP_CPU_MCU_IWDG_H_
#define BSP_CPU_MCU_IWDG_H_

#include <mcu-chip.h>

typedef R_IWDT_Type         IWDG_TypeDef;
typedef IWDG_TypeDef        IWDT_t;

enum {
    IWDT_SR_REFRESH_ERR = R_IWDT_IWDTSR_REFEF_Msk,
    IWDT_SR_UNDERFLOW   = R_IWDT_IWDTSR_UNDFF_Msk,
};



/* @note ClearXXXX only post iwdg for clear.
 * Read back status flags until required flag(s) cleared.
 * Flags cannot be cleared until after the clock cycle after they are set.
 * Described in hardware manual (see Section 26.2.2 'IWDT Status Register (IWDTSR)' of the RA6M3 manual R01UH0886EJ0100).
 */

static inline
void IWDG_StatusClearFlag( unsigned flags ){
    R_IWDT->IWDTSR = flags;
}

static inline
void IWDG_StatusClear( void ){
    R_IWDT->IWDTSR = IWDT_SR_REFRESH_ERR | IWDT_SR_UNDERFLOW;
}


/* function used to enable wdt in debug mode */
static inline
void enable_iwdt_count_in_debug_mode(void){
    /* As per hardware manual's DBGREG module, section 2.6.4.2:- Clear this bit to enable WDT Reset/NMI in debug mode */
    R_DEBUG->DBGSTOPCR_b.DBGSTOP_IWDT = 0;
}



#endif /* BSP_CPU_MCU_IWDG_H_ */
