Sam SunFish7

Microsecond Timer for HC9S12E128, 3 problems

Discussion created by Sam SunFish7 on Jun 17, 2007
Latest reply on Jul 7, 2007 by Jim Donelson
I need to accurately wait or measure small periods of time, say 20us +- error of 5us
x = MyTimer_GetElapsed_us();
once  I have this,  a microsecond delay routine should be easy:
void Delay_us(long us)
  while (MyTimer_GetElapsed_us() < us);
processor expert creates routines very close to what I need:
byte TimerBean_Reset(void)
  /* Load content of counter register to variable CntrState */
  CntrState = TIM0_TCNT; 
  return ERR_OK; 
byte TimerBean_GetCounterValue(word *Value)
  *Value = TIM0_TCNT;                  /* Return counter value */
  *Value -= CntrState;                 /* Subtract counter state */
                                       /* ... stored during last reset */
  return ERR_OK;                      
but it doesn't measure in microseconds;  I think it measures in jiffies.  The MCU is running at 16MHz, so that would give 16 jiffies to each microsecond.  and of course there are some overhead; Delay_us(0) is going to take up, say d_0  processor cycles.  So Delay_us(n) is equivalent  to delaying 16*n - d_0 jiffies.
so I put this in and test on the oscilloscope and it doesn't work properly.   the timings are always out.
this is the first problem.  how to code and accurate microsecond delay timer?
Second Problem   
while (1) PA^ = 0xff;
this creates a square wave on port A, frequency 0.5MHz.   but the process is running at 16MHz.  surely it cannot take 32 processor cycles!   I was working on an MSP430 and that took 4!  what is happening?  why  is it so slow?
Third Problem
I am needing to read/write binary  asynchronously to many pins.  that is why I need the above timing routines.
I am considering a new approach;  to poll the pins at 5us intervals.  so I need an interrupt to trigger every 5us: if there has been some activity,  it will be  queued up for processing later.
again processor expert generated some code that does this.   the problem is even though I specified that the interval should be 1us, I'm getting an interval of around 33us!!  is there some limitation?  I tried setting the priority to high, but that didn't change anything.  am I trying to do something unrealistic?
many thanks,