/* * Author: Jake G * Date: 2026 * filename: wwdg.c * description: Source for window watchdog implimentation. */ #include "wwdg.h" #include "RegEdit.h" #include "ch32fun.h" #define WWDG_MIN_WINDOW_VAL 0x40 // 64 #define WWDG_MAX_WINDOW_VAL 0x7F // 127 static inline void wwdg_rcc_enable(void) { // RegEdit_u32_AND_Num((void *)&RCC->APB1PCENR, RCC_WWDGEN); RegEdit_u32_SetBit((void *)&RCC->APB1PCENR, RCC_WWDGEN_BIT); } void wwdg_enable(void) { wwdg_rcc_enable(); RegEdit_u32_SetBit((void *)&WWDG->CTLR, WWDG_CTLR_WDGA_BIT); return; } // maybe this should actually set the reset bit in the APB1 reg? void wwdg_disable(void) { RegEdit_u32_ClearBit((void *)&RCC->APB1PCENR, RCC_WWDGEN_BIT); return; } bool wwdg_set_clock_div(uint8_t div) { if (div > 3) { return false; } RegEdit_u16_ClearBit((void *)&WWDG->CFGR, 7); RegEdit_u16_ClearBit((void *)&WWDG->CFGR, 8); RegEdit_u16_OR_Num((void *)&WWDG->CFGR, div); return true; } bool wwdg_set_window(uint8_t value) { // Check if either the input is bigger than 7-Bits or less than the min. if (value < WWDG_MIN_WINDOW_VAL || value > WWDG_MAX_WINDOW_VAL) { return false; } // First we clear the value in the first 7-Bits. // UINT16_MAX & ~127 = 0xFF80, aka bits [0:6] RegEdit_u16_AND_Num((void *)&WWDG->CFGR, 0xFF80); // Now we set the value. RegEdit_u16_OR_Num((void *)&WWDG->CFGR, value); return true; } bool wwdg_reset_timer(uint8_t reset_value) { if (reset_value > WWDG_MAX_WINDOW_VAL || reset_value < WWDG_MIN_WINDOW_VAL) { return false; } // Clear the last six bits RegEdit_u16_AND_Num((void *)&WWDG->CTLR, 0xFF80); // Set the last six bits. RegEdit_u16_OR_Num((void *)&WWDG->CTLR, reset_value); return true; } void wwdg_enable_interrupt(void) { RegEdit_u16_SetBit((void *)&WWDG->CFGR, WWDG_EWI_BIT); } void wwdg_disable_interrupt(void) { RegEdit_u16_ClearBit((void *)&WWDG->CFGR, WWDG_EWI_BIT); }