/*
             LUFA Library
     Copyright (C) Dean Camera, 2012.

  dean [at] fourwalledcubicle [dot] com
           www.lufa-lib.org
*/

// simplified and adapted by AP 2014
// updated for 32bit by MDK 2017
/*
  Copyright 2012  Dean Camera (dean [at] fourwalledcubicle [dot] com)
*/
#include <stdint.h>
#include "non_block_delay.h"

/**  Contains the current scheduler tick count, for use with the delay functions. If the delay functions
 *   are used in the user code, this should be incremented each tick period so that the delays can be
 *   calculated.
 */
volatile uint32_t tick_counter = 0;


void reset_delay(uint32_t *delay_counter)
{
    *delay_counter = tick_counter;
}
/*
* reset - reset afred delay occured?
  delay_counter - start delay_tick value for this delay
  delay = length of delay
 *  Usage Example:
 *  \code
 *      static uint16_t delay_counter = 10000; // Force immediate run on start-up
 *
 *      // Task runs every 10000 ticks, 10 seconds for this demo
 *      if (is_time_now(false, &delay_counter, delay))
 *      {
 *           // Code to execute after delay interval elapsed here
 *      }
 *  \endcode
 */
uint8_t is_time_now(uint8_t reset, uint32_t * delay_counter,  uint32_t delay)
{
    uint32_t actual_value;
    uint32_t local_delay;

    actual_value = tick_counter;
    local_delay = *delay_counter;

    if (actual_value >= local_delay )
    {
        if ((actual_value - local_delay) >= delay)
        {// delay elapsed
            if (reset)
               *delay_counter = actual_value;
            return 1;
        }
    }
    else
    {//overflow occured
        if (((0xFFFFFFFF - local_delay) + actual_value) >= delay)
        {
            if (reset)
                *delay_counter = actual_value;
            return 1;
        }
    }

return 0;
}


