Arduino 中断函数可以调用另一个函数吗?

Sai*_*aik 1 c++ arduino interrupt

我正在开发一个 Arduino 项目,在该项目中我通过 I2C 通信接收消息。我有几个例程,程序在其中花费了大量时间而没有返回。目前,我在发生中断时设置一个中断标志,我基本上在几个地方检查这些函数,如果发生中断,我就返回。我想知道中断函数是否可以调用我的入口点函数。

所以这是我目前的中断功能

void ReceivedI2CMessage(int numBytes)
{
    Serial.print(F("Received message = "));
    while (Wire.available())
    {
        messageFromBigArduino = Wire.read();
    }
    Serial.println(messageFromBigArduino);

    I2CInterrupt = true;
}
Run Code Online (Sandbox Code Playgroud)

在程序花费大部分时间的功能中,我不得不在几个地方这样做

if(I2CInterrupt) return;
Run Code Online (Sandbox Code Playgroud)

现在我想知道是否可以从我的 ReceiveI2CMessage 中调用我的入口点函数。我主要担心的是这可能会导致内存泄漏,因为当中断发生时我将正在执行的函数留在后面,然后我将返回到程序的开头。

Tom*_*rvo 5

没关系,但不是首选。少做一点总是更安全——也许只是设置一个标志——并尽可能快地退出中断。然后在主循环中处理标志/信号量。例如:

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
}
Run Code Online (Sandbox Code Playgroud)

然后在你的主循环中:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

这样就达到了中断的目的,理想情况下是在主循环中设置一个信号量来快速处理。

  • 在微控制器设计中,每 30 秒只访问一次主循环并不常见。这通常表明设计可以改进。但好消息是,如果您只是担心内存泄漏,即使很小的泄漏也会很快变得明显,因为这些设备上的 SRAM 非常小。坏消息是,如果您有泄漏,无论如何您都需要仔细检查您的设计。我建议从所有函数中快速返回,尤其是从中断中返回。 (2认同)