Hello, I'm rather new to Keil C and just getting geared up to use it on my next project. ATM, I'm overwhelmed with the number of options and extensions that are available. I intend to write a C "library" that consists of 3 functions:
Delay() DelayMS() DelayUS()
Delay(2); // creates a 2 second delay DelayMS(500); // creates 500ms delay DelayUS(10); // creates a 10us delay
Why? There's no need to do that. You can do everything in C. That would make the delay dependent on: 1) optimiser settings 2) compiler version 3) memory model so, to make it 'future safe' you must do it in assembler. Erik PS It's dead easy
I am a newbie to Keil and I am using 8051 based USB 2.0 device. Both IFCLK and CLKOUT are at 48Mhz. I want to implement a function that would introduce 1 microsecond delay. Can you please help?
I agree with Erik: even if you write it in 'C', you're going to have to look at the generated assembler to see how many NOPs to add anyhow - so why not just do it straight in assembler in the first place?! And, of course, with assembler WYSIWYG - you are not at the mercy of the compiler's and/or optimiser's whims! What I have done is to write two functions:
void Wait_1us( U8 n ); // Wait n+2 us void Wait_10us( U8 n ); // Wait 10n us
#define WAIT_1US( us ) Wait_1us( us-2 )
Just for the sake of variety: If you have a timer running, you can read the timer value to implement your delay loop. You don't have to set a timer value and code up an interrupt handler, or interfere with the existing use of the timer for another purpose. It's sufficient to read the timer, calculate your desired end value, and just spin while polling the timer value until the timer gets to the end. As with anything time-related, this is easiest to code if you know your delay time will be less than half the maximum range of the timer value.
Some time ago Jon Ward posted this macro here: http://www.keil.com/forum/docs/thread1940.asp You may find it useful for short delays:
#define NOPS(x) \ (((x) & 1) ? _nop_() : 0),\ (((x) & 2) ? _nop_(),_nop_() : 0),\ (((x) & 4) ? _nop_(),_nop_(),_nop_(),_nop_() : 0),\ (((x) & 8) ? _nop_(),_nop_(),_nop_(),_nop_(),_nop_(),_nop_(),_nop_(),_nop_() : 0)
Oh dear! My post did not do that on preview!