我如何在C中为Arduino创建中断



所以我在c中为Arduino编写了这个代码。它用于控制步进电机。但是每次我必须等到微控制器开始一个新的循环,以便它可以获取新变量的值,我怎么能创建一个中断,这样它就会在程序的任何时间?

#include <avr/io.h>
#define F_CPU 4000000UL
#include <util/delay.h>
#include "IO/ioconfig.h"
#include "leebotones/leebotonesA.h"
#include "leebotones/leebotonesB.h"
#include "rutina/avanza.h"
#include "rutina/retrocede.h"
char variableA = 0;
char variableB = 0;
int main(void){
    ioconfig();
    while(1) {
        if (leebotonesA()==1) {
            variableA++;
        } //Fin de if leebotonesA.
        if (leebotonesB()==1) {
            if (variableA==0) {
                variableB=1;
            }
            else {
                variableB=0;
            }
        }
        if (variableA==2) {
            variableA=0;
            PORTD=0x00;
            _delay_ms(10000);
        } //Fin de if variableA.
        if (variableA==1 && variableB==0) {
            avanza();
        } //Fin de if leebotonesA.
        if (variableA==1 && variableB==1) {
            retrocede();
        }
        _delay_ms(25);
    }//End of while
}// End of main

当其中一个中断引脚接收到状态变化时,Arduino上发生硬件中断。如果您可以访问Arduino库,那么要使用的函数是attachInterrupt。

监听中断的示例代码(来自我链接到的文档,我添加了注释来帮助解释):

// The Arduino has an LED configured at pin 13
int pin = 13;
// Holds the current state of the LED to handle toggling
volatile int state = LOW;
void setup()
{
  pinMode(pin, OUTPUT);
  // First Parameter:
  // 0 references the interrupt number. On the Duemilanove, interrupt 0
  // corresponds to digital pin 2 and interrupt 1 corresponds to digital pin
  // 3. There are only two interrupt pins for the Duemilanove and I believe
  // the Uno too.
  // Second Parameter:
  // blink is the name of the function to call when an interrupt is detected
  // Third Parameter:
  // CHANGE is the event that occurs on that pin. CHANGE implies the pin
  // changed values. There is also LOW, RISING, and FALLING.
  attachInterrupt(0, blink, CHANGE);
}
void loop()
{
  // Turns the LED on or off depending on the state
  digitalWrite(pin, state);
}
void blink()
{
  // Toggles the state
  state = !state;
}

还有一个在每个引脚上支持的引脚更改中断的概念。有关更多信息,请参阅中断介绍的底部部分。

然而,有时硬件中断可以通过重构代码来避免。例如,保持loop()快速运行——主要是读取输入,限制delay()的使用——并在循环中,在检测到目标输入值时调用函数。

MSTimer2是一个Arduino库函数,可以让你设置定时器中断。

延迟而不是中断的另一种替代方法是设置一个计时器,并在每次循环中检查它。http://arduino.cc/en/Tutorial/BlinkWithoutDelay解释了这些概念。Metro库http://arduino.cc/playground/Code/Metro实现了这一点,并且易于使用。我用它来代替delay(),这样我就可以在机器人移动时检查按钮是否按下。

最新更新