#include "systick.h"

#include "ch32v003fun.h"
#include "debug.h"

// ms counter
volatile uint32_t systick_millis = 0;

void init_systick(void) {
  SysTick->CTLR = 0;
  SysTick->CMP = SYSTICK_ONE_MILLISECOND - 1;
  SysTick->CNT = 0;
  systick_millis = 0;

  // Enable the SysTick IRQ
  NVIC_SetPriority(SysTicK_IRQn, 0xf0);
  NVIC_EnableIRQ(SysTicK_IRQn);
  /* Enable SysTick counter, IRQ, HCLK/1 */
  SysTick->CTLR = SYSTICK_CTLR_STE | SYSTICK_CTLR_STIE | SYSTICK_CTLR_STCLK;
}

/*
 * SysTick ISR - must be lightweight to prevent the CPU from bogging down.
 * Increments Compare Register and systick_millis when triggered (every 1ms)
 * NOTE: the `__attribute__((interrupt))` attribute is very important
 */
void SysTick_Handler(void) __attribute__((interrupt));
void SysTick_Handler(void) {
  // Increment the Compare Register for the next trigger
  // If more than this number of ticks elapse before the trigger is reset,
  // you may miss your next interrupt trigger
  // (Make sure the IQR is lightweight and CMP value is reasonable)
  SysTick->CMP += SYSTICK_ONE_MILLISECOND;

  // clear irq
  SysTick->SR = 0;
  systick_millis++;
}