#include "by_debug.h" #include "at32f415.h" #include "lwprintf.h" /* delay macros */ #define STEP_DELAY_MS 50 /* delay variable */ static __IO uint32_t fac_us; static __IO uint32_t fac_ms; int lwprintf_out(int ch, lwprintf_t *lwp) { /* May use printf to output it for test */ if (ch != '\0') { while (usart_flag_get(BY_DEBUG_USART_INDEX, USART_TDC_FLAG) == RESET); usart_data_transmit(BY_DEBUG_USART_INDEX, (char)ch); } return ch; } void by_debug_init(void) { lwprintf_init(lwprintf_out); } void delay_init(void) { systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_DIV8); crm_clocks_freq_type clocks; crm_clocks_freq_get(&clocks); fac_us = clocks.sclk_freq / (8000000U); fac_ms = fac_us * (1000U); } /** * @brief inserts a delay time. * @param nus: specifies the delay time length, in microsecond. * @retval none */ void delay_us(uint32_t nus) { uint32_t temp = 0; SysTick->LOAD = (uint32_t)(nus * fac_us); SysTick->VAL = 0x00; SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; do { temp = SysTick->CTRL; } while ((temp & 0x01) && !(temp & (1 << 16))); SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; SysTick->VAL = 0x00; } /** * @brief inserts a delay time. * @param nms: specifies the delay time length, in milliseconds. * @retval none */ void delay_ms(uint16_t nms) { uint32_t temp = 0; while (nms) { if (nms > STEP_DELAY_MS) { SysTick->LOAD = (uint32_t)(STEP_DELAY_MS * fac_ms); nms -= STEP_DELAY_MS; } else { SysTick->LOAD = (uint32_t)(nms * fac_ms); nms = 0; } SysTick->VAL = 0x00; SysTick->CTRL |= SysTick_CTRL_ENABLE_Msk; do { temp = SysTick->CTRL; } while ((temp & 0x01) && !(temp & (1 << 16))); SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; SysTick->VAL = 0x00; } } /** * @brief inserts a delay time. * @param sec: specifies the delay time, in seconds. * @retval none */ void delay_sec(uint16_t sec) { uint16_t index; for (index = 0; index < sec; index++) { delay_ms(500); delay_ms(500); } }