[英]Arduino Is it ok for an interrupt function to call another function?
我正在一個Arduino項目中,通過I2C通信接收消息。 我有兩個例程,程序在其中花費了很多時間而沒有返回。 目前,我會在發生中斷時設置一個中斷標志,基本上我會在幾個地方檢查這些功能,如果發生中斷,我會返回。 我想知道是否可以讓中斷函數代替我的入口點函數。
這是我目前的中斷功能
void ReceivedI2CMessage(int numBytes)
{
Serial.print(F("Received message = "));
while (Wire.available())
{
messageFromBigArduino = Wire.read();
}
Serial.println(messageFromBigArduino);
I2CInterrupt = true;
}
在程序大部分時間所使用的功能中,我不得不在幾個地方執行此操作
if(I2CInterrupt) return;
現在我想知道是否可以從ReceiveI2CMessage內部調用入口點函數。 我主要擔心的是,這可能會導致內存泄漏,因為當發生中斷時,我將正在執行的功能留在后面,而我將回到程序的開頭。
可以,但不是首選。 少做事總是比較安全的-也許只需設置一個標志-並盡快退出中斷。 然后,在主循環中照顧好標志/信號燈。 例如:
volatile uint8_t i2cmessage = 0; // must be volatile since altered in an interrupt
void ReceivedI2CMessage(int numBytes) // not sure what numBytes are used for...
{
i2cmessage = 1; // set a flag and get out quickly
}
然后在您的主循環中:
loop()
{
if (i2cmessage == 1) // act on the semaphore
{
cli(); // optional but maybe smart to turn off interrupts while big message traffic going through...
i2cmessage = 0; // reset until next interrupt
while (Wire.available())
{
messageFromBigArduino = Wire.read();
// do something with bytes read
}
Serial.println(messageFromBigArduino);
sei(); // restore interrupts if turned off earlier
}
}
這樣可以達到中斷的目的,理想情況下,該目標是設置一個信號量,使其在主循環中快速起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.