//
// Created by dell on 24-9-23.
//

#ifndef ULTRASONIC_DRIVER_H
#define ULTRASONIC_DRIVER_H

#include "gd32e23x.h"

#define POWER_SUPPLY_12V
// #define POWER_SUPPLY_24V

#ifdef POWER_SUPPLY_12V
#define TIME_CORRECTION_US  250
#define CAPTURE_VALUE_MAX   515
#elif defined(POWER_SUPPLY_24V)
#define TIME_CORRECTION_US  230
#define CAPTURE_VALUE_MAX   550
#else
    #error "Please define either POWER_SUPPLY_12V or POWER_SUPPLY_24V"
#endif

#define ULTRASONIC_CYCLES   0x05U
#define ULTRASONIC_TRAN_US  500  // (ms)

#define LED_PORT            GPIOA
#define LED_PIN             GPIO_PIN_9
#define LED_RCU             RCU_GPIOA
#define LED_TIMER_RCU       RCU_TIMER5
#define LED_TIMER           TIMER5
#define LED_IRQ             TIMER5_IRQn

#define USART_RCU            RCU_USART0
#define USART_GPIO_RCU       RCU_GPIOA
#define USARET_GPIO_PORT     GPIOA
#define USART_TX_PIN         GPIO_PIN_2
#define USART_RX_PIN         GPIO_PIN_3
#define USART0_PHY           USART0
#define USART_BAUDRATE       115200U

#define US_TRAN_GPIO_RCU     RCU_GPIOB
#define US_TRAN_GPIO_PORT    GPIOB
#define US_TRAN_PIN          GPIO_PIN_1
#define US_TRAN_AF           GPIO_AF_0

#define US_TRAN_RCU          RCU_TIMER13
#define US_TRAN_TIMER        TIMER13
#define US_TRAN_CH           TIMER_CH_0

#define US_TRAN_DELAY_RCU     RCU_TIMER15
#define US_TRAN_DELAY_TIMER   TIMER15

#define US_FB_GPIO_RCU       RCU_GPIOA
#define US_FB_EXTI_RCU       RCU_CFGCMP
#define US_FB_GPIO_PORT      GPIOA
#define US_FB_GPIO_PIN       GPIO_PIN_0
#define US_FB_EXTI_IRQ       EXTI0_1_IRQn
#define US_FB_GPIO_EXTI      EXTI_0

#define US_ECHO_RCU          RCU_TIMER16
#define US_ECHO_TIMER        TIMER16
#define US_ECHO_CH           TIMER_CH_0

void led_config(void);
void usart_config(void);
void ultrasonic_config(void);
void ultrasonic_transmit_config(void);
void ultrasonic_pwm_out_cycles(const uint8_t cycles);
void ultrasonic_transmit_delay(const uint16_t micro_second);
void receive_exti_config(void);
void ultrasonic_echo_timer_config(void);
void ultrasonic_receive_config(void);
uint16_t calculate_distance(uint32_t us_value);

#endif //ULTRASONIC_DRIVER_H
