Arduino在中斷函數(shù)里面怎么延時Arduino里面有兩種中斷,一種是內(nèi)部中斷,就象系統(tǒng)時鐘那樣,一直在那兒持續(xù),輪詢到中斷信號,以最高的優(yōu)先級去執(zhí)行。另一種是外部中斷,輸入中斷信號,以低于內(nèi)部中斷的優(yōu)先級去執(zhí)行。 一般用不上中斷,但中斷異常重要。因為loop里面的耗時的動作,例如持續(xù)不停的for循環(huán),for之外的動作,只能等到for之后再去執(zhí)行。如果正在for的時候需要另一個緊急任務,或者無條件去執(zhí)行的任務,就只能使用中斷了。中斷有些象應急搶險系統(tǒng),無論什么情況,只要中斷信號來了,無條件去執(zhí)行。 據(jù)資料介紹,中斷會打斷代碼的正常執(zhí)行次序,所以中斷函數(shù)里不能使用諸如millis()、 delay()等由中斷實現(xiàn)的延時函數(shù)。 又有資料說可以使用 delayMicroseconds(),因為這個函數(shù)與中斷無關。但是試用之下,感覺似乎并沒有起到延時的作用,很可能它也不能使用。搜索一下有沒有人解決這個問題呢,確實有人遇到類似問題,已經(jīng)解決。 LED發(fā)光二極管3只,220R電阻3只,1K電阻1只。 
接線如圖:

設置997ms輪詢1次內(nèi)部中斷,觸發(fā)則使D1亮2000ms熄滅。電鍵由打開到閉合,觸發(fā)則使D2亮2000ms熄滅。接線后,執(zhí)行代碼,D1亮暗幾次后,節(jié)奏紊亂,說明997ms輪詢和2000ms延時有效。電鍵閉合,若閉合時D3為熄滅狀態(tài),D2亮起后,約2000ms后D3重復亮起,說明中斷函數(shù)中的延時有效。
代碼: #include <MsTimer2.h>//需MsTimer2庫 const int led_pin7 = 7;//內(nèi)部中斷LED腳 const int led_pin6 = 6; //外部中斷LED腳 const int led_pin5 = 5; //自己閃的LED const int pinInterrupt = 2;//外部中斷信號輸入 ////////////////////軟件延時/////////////////////// #define NOP do { __asm__ __volatile__ ("nop"); } while (0) #define ulong unsigned long void delay_(int ms) { for (int i = 0; i < ms; i++) { for (ulong j = 0; j < 1985; j++) NOP; } } ///////////////////////////////////////////////// void flash7() { //使用自己的delay_才能正確延時 static boolean output = HIGH; digitalWrite(led_pin7, output); delay_(2000); output = !output; }
void flash6() { if ( digitalRead(pinInterrupt) == LOW ) { digitalWrite(led_pin6, HIGH); delay_(2000); } else { digitalWrite(led_pin6, LOW); } }
void setup() { pinMode(led_pin7, OUTPUT); pinMode(led_pin6, OUTPUT); pinMode(led_pin5, OUTPUT); pinMode(pinInterrupt, INPUT); //內(nèi)部中斷鉤子 MsTimer2::set(977, flash7); //997毫秒輪詢一次 MsTimer2::start(); //外部中斷鉤子 attachInterrupt( digitalPinToInterrupt(pinInterrupt), flash6, CHANGE); }
void loop() { digitalWrite(led_pin5, HIGH); delay(157); digitalWrite(led_pin5, LOW); delay(137); }
|