Arduino - 中斷



中斷會停止 Arduino 當前的工作,以便可以執行其他工作。

假設你坐在家裡,與某人聊天。突然電話響了。你停止聊天,拿起電話與來電者通話。當你結束電話交談後,你回到之前電話響之前與那個人的聊天。

同樣,你可以將主程式想象成與某人聊天,電話響了導致你停止聊天。中斷服務程式是接聽電話的過程。當電話交談結束時,你回到你聊天這一主程式。此示例準確地解釋了中斷如何導致處理器採取行動。

主程式正在執行並在電路中執行某些功能。但是,當發生中斷時,主程式會暫停,同時執行另一個程式。當此程式結束時,處理器再次返回主程式。

Interrupt

重要特性

以下是關於中斷的一些重要特性:

  • 中斷可以來自各種來源。在本例中,我們使用硬體中斷,該中斷由某個數字引腳的狀態變化觸發。

  • 大多數 Arduino 設計有兩個硬體中斷(稱為“interrupt0”和“interrupt1”),分別硬連線到數字 I/O 引腳 2 和 3。

  • Arduino Mega 有六個硬體中斷,包括引腳 21、20、19 和 18 上的其他中斷(“interrupt2”到“interrupt5”)。

  • 您可以使用一個稱為“中斷服務程式”(通常稱為 ISR)的特殊函式來定義程式。

  • 您可以定義程式並指定上升沿、下降沿或兩者處的條件。在這些特定條件下,將服務中斷。

  • 可以使該函式在輸入引腳上每次發生事件時自動執行。

中斷型別

有兩種型別的中斷:

  • 硬體中斷 - 它們是響應外部事件發生的,例如外部中斷引腳變高或變低。

  • 軟體中斷 - 它們是響應軟體中傳送的指令發生的。“Arduino 語言”支援的唯一中斷型別是 attachInterrupt() 函式。

在 Arduino 中使用中斷

中斷在 Arduino 程式中非常有用,因為它有助於解決定時問題。中斷的一個很好的應用是讀取旋轉編碼器或觀察使用者輸入。通常,ISR 應該儘可能短且快速。如果你的程式使用多個 ISR,則一次只能執行一個。其他中斷將在當前中斷完成後按順序執行,執行順序取決於它們的優先順序。

通常,全域性變數用於在 ISR 和主程式之間傳遞資料。為了確保在 ISR 和主程式之間共享的變數正確更新,請將其宣告為易失性。

attachInterrupt 語句語法

attachInterrupt(digitalPinToInterrupt(pin),ISR,mode);//recommended for arduino board
attachInterrupt(pin, ISR, mode) ; //recommended Arduino Due, Zero only
//argument pin: the pin number
//argument ISR: the ISR to call when the interrupt occurs; 
   //this function must take no parameters and return nothing. 
   //This function is sometimes referred to as an interrupt service routine.
//argument mode: defines when the interrupt should be triggered.

以下三個常量被預定義為有效值:

  • LOW 當引腳為低電平時觸發中斷。

  • CHANGE 當引腳值發生變化時觸發中斷。

  • FALLING 當引腳從高電平變為低電平時觸發中斷。

示例

int pin = 2; //define interrupt pin to 2
volatile int state = LOW; // To make sure variables shared between an ISR
//the main program are updated correctly,declare them as volatile.

void setup() {
   pinMode(13, OUTPUT); //set pin 13 as output
   attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);
   //interrupt at pin 2 blink ISR when pin to change the value
} 
void loop() { 
   digitalWrite(13, state); //pin 13 equal the state value
} 

void blink() { 
   //ISR function
   state = !state; //toggle the state when the interrupt occurs
}
廣告