/********************************** (C) COPYRIGHT *******************************
* File Name          : main.c
* Author             : WCH
* Version            : V1.0.0
* Date               : 2021/06/06
* Description        : Main program body.
*********************************************************************************
* 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.
*******************************************************************************/

/*
 *@Note
 BKP routine:
 Intrusion detection pin (PC13), when an intrusion detection event occurs, all data backup register contents are cleared,
   And trigger the intrusion detection interrupt.

*/

#include "debug.h"


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


/*********************************************************************
 * @fn      GPIO_Toggle_INIT
 *
 * @brief   Initializes GPIOA.0
 *
 * @return  none
 */
void GPIO_Toggle_INIT(void)
{
    GPIO_InitTypeDef GPIO_InitStructure = {0};

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
}


//SysTick初始化配置
static uint32_t SysTick_Config(uint64_t ticks)
{
    SysTick->CTLR = 0x0000;                  //关闭系统计数器STK，计数器停止计数

    //设置系统计数器寄存器的值
    SysTick->CNT = 0;

    //设置计数比较寄存器的值，主要用于触发STK中断服务函数。当CNT[63:0]与CMP[63:0]值相等时将触发STK中断服务。
    SysTick->CMP = (u64)(ticks);

    NVIC_SetPriority(SysTicK_IRQn, 15);      //设置SysTick中断优先级
    NVIC_EnableIRQ(SysTicK_IRQn);            //使能开启Systick中断

    SysTick->CTLR |=  (1 << 5) | (1 << 3)| (1 << 1) | (1 << 0);                  //启动系统计数器STK（HCLK/8时基） 72000000/8=9000000

    return (0);
}

void Systick_Init(void)
{
    //此处在进行初始化的时候设置比较寄存器的值
    SysTick_Config(SystemCoreClock / 8000);//            72M/8000/9000000 = 1/1000 = 1ms
}
u8 i=0;
//关于STK中断服务函数，由于STK的时基为HCLK/8，且在SysTick初始化配置中设置比较寄存器的值为SystemCoreClock / 8000 = 9000，由此计算的每隔1ms触发1次中断服务函数
void SysTick_Handler(void)
{
    GPIO_WriteBit(GPIOA, GPIO_Pin_0, (i == 0) ? (i = Bit_SET) : (i = Bit_RESET));

    SysTick->SR=0;
}


/*********************************************************************
 * @fn      main
 *
 * @brief   Main program.
 *
 * @return  none
 */
int main(void)
{
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
//    Delay_Init();
    USART_Printf_Init(115200);
    GPIO_Toggle_INIT();


    Systick_Init();
    printf("SystemClk:%d\r\n", SystemCoreClock);

    printf("This is printf example\r\n");
    while(1)
    {

    }
}


