How should I write a delay macro for an PIC 18f87J50 with a 48MHz crystal and compiler of MCC18. The delay should be in us. So I for example can write: Delay_us(201) and really get 201us delay.
What I have now is:
#define Delay_us(n) (Delay10TCYx(((n) * (uint16_t) 12 + 9) / 10))
And it doesn't seem right at my oscilloscope! :/
The PIC divides the clock by 4 so for 48Mhz each opcode runs in 0.0833us or 12 cycles per us. I used MPLAB and put in different us values and checked in the simulator so that the number of cycles came out as I expected. The best way to adjust the function is to look at the assembly or use the simulator.
You can do something like the following but you will have to adjust the function call for your complier.
#define OVERHEAD (2)
void Delay_us(uint8_t us)
{
if ( us <= OVERHEAD ) return; // prevent underflow
us -= OVERHEAD ; // overhead of function call in us.
Nop(); // 1 extra overhead to make function overhead an even us.
Nop(); // 1 add or remove Nop's as necessary.
Nop(); // 1
//Nop(); // 1
//Nop(); // 1
//Nop(); // 1
//Nop(); // 1
//Nop(); // 1
//Nop(); // 1
//Nop(); // 1
//Nop(); // 1
//Nop(); // 1
do // loop needs to be 12 cycles so each cycle is 1us.
{
Nop(); // 1
Nop(); // 1
Nop(); // 1
Nop(); // 1
Nop(); // 1
Nop(); // 1
Nop(); // 1
Nop(); // 1
ClrWdt(); // 1
} while(--us); // 3
}