/*
    (C) 2017 Renesas Electronics Corporation.
     This software is released under the terms and conditions described in LICENSE_RENESAS.TXT included in the project.
*/
/**
  * @file    rl78g14_delay.h
  * @author  Renesas Electronics Corporation
  * @brief   Sample delay functions program header.
**/

#ifndef __RP_RL78G14_DELAY_H__
#define __RP_RL78G14_DELAY_H__

#define RP_DELAY_MAX_MS 50000	//maximum time delay function can handle in millisecond. valid parameter is 1 to 65535.
#define HAL_Delay RpMcuDelay

#define HAL_DelayUs RpMcuDelayUs

/*!
 *\brief Provides delay (in ms) based on the counter of TAU01(Timer Array Unit, unit 0, channel 1).
 *\param[in] delay specifies the delay time length, in milliseconds. valid argument is 0 to RP_DELAY_MAX_MS ms.
 * \return None.
 */
void RpMcuDelay(uint32_t delay);

void RpMcuDelayUs(unsigned delay_us);

//import: NOP
#include <utilities.h>

//! @brief 1 CPU cycle delay.
#define RP_CPU_1CYCLE_NS (1000/RP_CPU_CLK)

#define RP_DELAY_TICKS( n ) {\
    if ( (n) >= 7) { RpDelayTicks(n); }\
    else if ( (n) >= 4) {__NOP();__NOP(); __NOP();__NOP();}\
    else if ( (n) >= 3) {__NOP();__NOP();__NOP();}\
    else if ( (n) >= 2) {__NOP();__NOP();}\
    else if ( (n) >= 1) __NOP();\
    }

#define RP_DELAY_NS( ns )  RP_DELAY_TICKS( ((ns) + RP_CPU_1CYCLE_NS - 5) / RP_CPU_1CYCLE_NS )

static inline
void RpDelayTicks(unsigned n){
    for (; n > 3; n -=3 ) __NOP();
}

#endif //#ifndef __RP_RL78G14_DELAY_H__
