/********************************** (C) COPYRIGHT *******************************
 * File Name          : ch32v00x_it.c
 * Author             : WCH
 * Version            : V1.0.0
 * Date               : 2022/08/08
 * Description        : Main Interrupt Service Routines.
*********************************************************************************
* Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd.
* Attention: This software (modified or not) and binary are used for 
* microcontroller manufactured by Nanjing Qinheng Microelectronics.
*******************************************************************************/
#include <ch32v00x_it.h>
#include <ch32v00x.h>

#include "src/adc.h"
#include "src/btn.h"
#include "src/led.h"



void NMI_Handler(void);
void HardFault_Handler(void);
void SysTick_Handler(void) __attribute__((interrupt("WCH-Interrupt-fast")));



/*********************************************************************
 * @fn      NMI_Handler
 *
 * @brief   This function handles NMI exception.
 *
 * @return  none
 */
void NMI_Handler(void)
{
}

/*********************************************************************
 * @fn      HardFault_Handler
 *
 * @brief   This function handles Hard Fault exception.
 *
 * @return  none
 */
void HardFault_Handler(void)
{
    while (1);
}


volatile uint16_t ticnt;
volatile uint32_t uptime;

void SysTick_Handler(void)
{
    if (++ticnt > 0x1ff) {
        ticnt = 0;
        uptime++;
    }

    // send new LEDs (1/128 duty)
    if ((ticnt & 0x3) == 0) {
        led_send();
    }

    // process buttons (1/512 duty)
    btn_poll();

    // process ADC (1/256 duty)
    if ((ticnt & 0x1) == 0) {
        adc_convert();
    }
    if ((ticnt & 0x1) == 1) {
        adc_read();
    }

    // clear comparison flag
    SysTick->SR = 0;

    return;
}
