/*
 * timer.c
 *
 *  Created on: Jun 25, 2023
 *      Author: true
 */


#include "hk32f030m.h"



/*
 * main code loop setup
 */
void tim6_init()
{
    NVIC_InitTypeDef nvic;

    // enable timer clock
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE);

    // configure timer for continuous 1KHz interrupt rate
    TIM6->CR1  = 0;							// default settings
    TIM6->CNT  = 0;							// clear count
    TIM6->PSC  = 16 - 1;					// set prescale
    TIM6->ARR  = (2000000 / 1024) - 1;		// set interrupt frequency
    TIM6->EGR  = TIM_EGR_UG;				// reload values

    // enable timer, send update event, clear interrupt then enable interrupt
    TIM6->SR   = 0;							// clear interrupt if set
    TIM6->CR1  = TIM_CR1_ARPE | \
    		TIM_CR1_URS | TIM_CR1_CEN;		// enable timer as upcounter
    TIM6->DIER = TIM_DIER_UIE;				// enable interrupt source

    // configure and enable IRQ
	nvic.NVIC_IRQChannel = TIM6_IRQn;
	nvic.NVIC_IRQChannelPriority = 1;
	nvic.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&nvic);
}
