很多用arduino單片機進行電子設計的同學有很多會涉及中斷函數的編寫,但是對於中斷函數中有需要編寫延時函數時,常常會有同學碰到很多麻煩。現對中斷函數中如何進行延時函數編寫做下總結,對大家可能想到的方法做下介紹。
- for循環
在一般的程序裏面我們可以採用三層for循環來實現一般的延時,網上也有針對不同計時器的小軟件來幫忙計算i,j,k的值
for(i=0;i<256;i++)
for(j=o;j<256;j++)
for(k=0;k<256;k++)
但是在arduino的中斷函數裏面對於 空操作有優化,會把空操作快速執行,不能達到延時效果。
- delay函數
delay函數是arduino內的自帶的最常用的延時函數,但是它調用avr的timer0,和中斷函數衝突,也是無法起作用的。
- 正解 delayMicroseconds函數
for(int i=0;i<100;i++)
delayMicroseconds(10000);
可以使用上述的方法實現在中斷函數中的延時,delaymicrosecond()不是使用計時器,而是用avr彙編的loop循環來實現的,所以在中斷中,這個函數依然可以起作用。但是注意不要影響下一次的中斷的進入,這個函數是微秒級的,最大是16383
Description
Pauses the program for the amount of time (in microseconds) specified as parameter. There are a thousand microseconds in a millisecond, and a million microseconds in a second.
Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay()
instead.
上述說明是arduino對該函數的描述,供大家參考!