/*!
    \file    main.c
    \brief   led spark with systick, USART print and key example

    \version 2024-02-22, V2.1.0, firmware for GD32E23x
*/
// #include "main.h"
#include <stdio.h>
#include "gd32e23x.h"
#include "systick.h"
#include "gd32e23x_libopt.h"

#include "ultrasonic_driver.h"

extern uint32_t capture_value;
uint16_t distance_uint16;

/*!
    \brief      main function
    \param[in]  none
    \param[out] none
    \retval     none
*/
int main(void)
{
    /* configure systick */
    systick_config();
    /* configure ultrasonic board hardware */
    ultrasonic_transmit_config();
    ultrasonic_recevice_config();

    /* ---------- debug start ---------- */




    /* ---------- debug end ---------- */

    printf("\r\n");
    printf("XLSW-3DP-UltraSonic Analog 300K!\r\n");
    printf("\r\n");

    delay_ms(2000);

    while(1)
    {
        delay_ms(ULTRASONIC_TRAN_US);

        ultrasonic_pwm_out_cycles(ULTRASONIC_CYCLES);

        delay_ms(2);
        printf("cap_val:%ld\t", capture_value);

        const char* result = (capture_value <= CAPTURE_VALUE_MAX) ? "Distance: %d\n" : "Over Range\n";
        distance_uint16 = calculate_distance(capture_value);
        printf(result, distance_uint16);
    }
}

/* retarget the C library printf function to the USART */
int _write (int fd, char *pBuffer, int size) {
    for (int i = 0; i < size; i++)
    {
        usart_data_transmit(USART0, (uint8_t)pBuffer[i]);
        while(RESET == usart_flag_get(USART0, USART_FLAG_TBE));
    }
    return size;
}
