/**
 ******************************************************************************
 * @file    clock.c
 * @author  cuij
 * @version V1.0.0
 * @date    11-02-2023
 * @brief   The  code is that use adapted to Arduino interface
 *
 * @par         Project
 *              MG32x02z
 * @author      Megawin Software Center
 * @copyright   Copyright (c) 2023 MegaWin Technology Co., Ltd.
 *              All rights reserved.
 * 
  ******************************************************************************
  Copyright (c) 2023 megawin Technology Co., Ltd. All rights reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the GNU Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "MG32x02z.h"
#include "system_MG32x02z.h"
#include "MG32x02z_GPIO.h"
#include "MG32x02z_TM.h"
#include "hw_config.h"
#include "timer.h"
#include "digital_io.h"
#include "variant.h"

#ifdef __cplusplus
 extern "C" {
#endif


uint32_t GetCurrentMicro(void)
{
    uint32_t MicroTick = 0;
    uint32_t LoadTick = (SysTick->LOAD);
    uint32_t NowTick  = (SysTick->VAL);
    
    uint32_t  CRT = MID_CSC_GetCK_AHBFreq()/1000000;

    MicroTick = LoadTick - NowTick;
    MicroTick = MicroTick / CRT;

    return ((uint32_t)MID_GetTick()*1000) + MicroTick;
}

/**
  * @brief  Function called wto read the current millisecond
  * @param  None
  * @retval None
  */
uint32_t GetCurrentMilli(void)
{
    return MID_GetTick();
}



/**
  * @brief  Function provides us delay (required by some arduino libraries).
  *         Can be called inside an interrupt.
  * @param  None
  * @retval None
  */
void delayInsideIT(uint32_t delay_us)
{
  uint32_t nb_loop;

  nb_loop = (((HAL_RCC_GetHCLKFreq() / 1000000)/5)*delay_us)+1; /* uS (divide by 4 because each loop take about 4 cycles including nop +1 is here to avoid delay of 0 */
  __asm__ volatile(
  "1: " "\n\t"
  " nop " "\n\t"
  " sub %0, %0, #1 " "\n\t"
  " bne 1b " "\n\t"
  : "=r" (nb_loop)
  : "0"(nb_loop)
  : "r3"
  );
}



#ifdef __cplusplus
}
#endif




