/**************************************************************************************
 Copyright (c) 2002
      The UbixOS Project

 $Id: delay.c,v 1.5 2002/04/29 23:34:57 reddawg Exp $
**************************************************************************************/

#include <ubixos/delay.h>

long delayCount=1,ticks=0;

long calibrateDelayLoop(void) {
  unsigned int prevtick,i,calib_bit;
  do {
    delayCount<<=1;
    prevtick=ticks;
    while(prevtick==ticks);
    prevtick=ticks;
    _delay(delayCount);
   } while(prevtick==ticks);
  delayCount>>=1;
  calib_bit=delayCount;
  for (i=0;i<PRECISION;i++) {
    calib_bit>>=1;
    if(!calib_bit) break;
    delayCount|=calib_bit;
    prevtick=ticks;
    while(prevtick==ticks);
    prevtick=ticks;
    _delay(delayCount);
    if (prevtick!=ticks) delayCount&=~calib_bit;
    }
  delayCount/=MILLISEC;
  return delayCount;
  }

void _delay(long loops) {
  long c;
  for(c=0;c<loops;c++);
  }

void delay(long miliseconds) {
  _delay(miliseconds*delayCount);
  }