/* Delay for the given number of microseconds. Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */voiddelayMicroseconds(unsignedintus){// call = 4 cycles + 2 to 4 cycles to init us(2 for constant delay, 4 for variable)
// calling avrlib's delay_us() function with low values (e.g. 1 or
// 2 microseconds) gives delays longer than desired.
//delay_us(us);
// for the 16 MHz clock on most Arduino boards
// for a one-microsecond delay, simply return. the overhead
// of the function call takes 14 (16) cycles, which is 1us
if(us<=1)return;// = 3 cycles, (4 when true)
// the following loop takes 1/4 of a microsecond (4 cycles)
// per iteration, so execute it four times for each microsecond of
// delay requested.
us<<=2;// x4 us, = 4 cycles
// account for the time taken in the preceding commands.
// we just burned 19 (21) cycles above, remove 5, (5*4=20)
// us is at least 8 so we can subtract 5
us-=5;// = 2 cycles,
// busy wait
__asm____volatile__("1: sbiw %0,1""\n\t"// 2 cycles
"brne 1b":"=w"(us):"0"(us)// 2 cycles
);// return = 4 cycles
}
入力はunsinged int型の変数です。戻り値はありません。
引数が1以下であれば、すでに1マイクロ秒経過しているので、何もしないでリターンします。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* Delay for the given number of microseconds. Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */voiddelayMicroseconds(unsignedintus){// call = 4 cycles + 2 to 4 cycles to init us(2 for constant delay, 4 for variable)
// calling avrlib's delay_us() function with low values (e.g. 1 or
// 2 microseconds) gives delays longer than desired.
//delay_us(us);
// for the 16 MHz clock on most Arduino boards
// for a one-microsecond delay, simply return. the overhead
// of the function call takes 14 (16) cycles, which is 1us
if(us<=1)return;// = 3 cycles, (4 when true)
次に入力された引数を4倍(左に2ビットシフト)し、5を引きます。
16
17
18
19
20
21
22
23
24
// the following loop takes 1/4 of a microsecond (4 cycles)
// per iteration, so execute it four times for each microsecond of
// delay requested.
us<<=2;// x4 us, = 4 cycles
// account for the time taken in the preceding commands.
// we just burned 19 (21) cycles above, remove 5, (5*4=20)
// us is at least 8 so we can subtract 5
us-=5;// = 2 cycles,