我正在开发一个 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
}
}
这样就达到了中断的目的,理想情况下是在主循环中设置一个信号量来快速处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句