/*!
    \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 "RS485.h"
#include "LDC1612.h"

void led_config(void)
{
    rcu_periph_clock_enable(LED_RCU);

    gpio_mode_set(LED_PORT, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, LED_PIN);
    gpio_output_options_set(LED_PORT, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, LED_PIN);
    gpio_bit_write(LED_PORT, LED_PIN, SET);

    rcu_periph_clock_enable(LED_TIMER_RCU);
    timer_deinit(LED_TIMER);

    timer_parameter_struct timer_initpara;
    timer_struct_para_init(&timer_initpara);
    timer_initpara.prescaler = 799;
    timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
    timer_initpara.counterdirection = TIMER_COUNTER_UP;
    timer_initpara.period = 999;
    timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
    timer_init(LED_TIMER, &timer_initpara);

    timer_auto_reload_shadow_enable(LED_TIMER);
    timer_interrupt_enable(LED_TIMER, TIMER_INT_UP);

    timer_enable(LED_TIMER);

    nvic_irq_enable(LED_IRQ, 2);
}

/*!
    \brief      main function
    \param[in]  none
    \param[out] none
    \retval     none
*/
int main(void) {
    /* configure systick */
    systick_config();
    RS485_config();
    led_config();
    I2C_config();

    printf("\r\n");
    printf("XLSW-3DP-LDC1612! V0.0.1\r\n");
    printf("\r\n");

    delay_ms(500);

    // int result = 0;
    uint16_t data = 0;
    uint16_t device_id = 0;
    LDC1612_IIC_read_16bits(READ_DEVICE_ID, &data);
    // printf("result = %d\r\n", result);


    // delay_ms(1000);


    LDC1612_IIC_read_16bits(READ_DEVICE_ID, &device_id);
    printf("Manufacturer: 0x%x\r\n", data);
    printf("Device: 0x%x\r\n", device_id);

    while (1) {
        delay_ms(1000);
        printf("OK!!!\r\n");
    }
}

/* 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;
}
