如何在C语言中为Arduino创建中断?
所以我用C语言为Arduino编写了这个代码。它是用来控制步进电机的。但是每次我必须等到微控制器开始一个新的循环,这样它才能获取新变量的值,我怎么才能创建一个中断,这样它就可以在程序的任何时候执行它呢如何在C语言中为Arduino创建中断?,c,arduino,C,Arduino,所以我用C语言为Arduino编写了这个代码。它是用来控制步进电机的。但是每次我必须等到微控制器开始一个新的循环,这样它才能获取新变量的值,我怎么才能创建一个中断,这样它就可以在程序的任何时候执行它呢 #include <avr/io.h> #define F_CPU 4000000UL #include <util/delay.h> #include "IO/ioconfig.h" #include "leebotones/leebotonesA.h" #includ
#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
#包括
#定义F_CPU 4000000UL
#包括
#包括“IO/ioconfig.h”
#包括“leebotones/leebotonesA.h”
#包括“leebotones/leebotonesB.h”
#包括“rutina/avanza.h”
#包括“rutina/retrocede.h”
字符变量a=0;
char variableB=0;
内部主(空){
ioconfig();
而(1){
如果(leebotonesA()==1){
变量a++;
}//如果是利博通萨的话。
如果(leebotonesB()==1){
如果(变量a==0){
变量b=1;
}
否则{
变量b=0;
}
}
如果(变量a==2){
变量a=0;
端口D=0x00;
_延迟(10000);
}//如果变量为,则为Fin de。
if(variableA==1&&variableB==0){
avanza();
}//如果是利博通萨的话。
if(variableA==1&&variableB==1){
追溯();
}
_延迟时间(25);
}//结束
}//干管末端
当一个中断引脚接收到状态变化时,Arduino上发生硬件中断。如果您可以访问Arduino库,则要使用的函数为
侦听中断的示例代码(源自我链接的文档,我添加了注释以帮助解释):
每个引脚上都支持引脚更改中断的概念。有关详细信息,请参见的底部
然而,有时通过重构代码可以避免硬件中断。例如,保持loop()快速运行—主要是读取输入,限制delay()的使用—并在循环中,在检测到目标输入值时调用函数。MSTimer2是一个Arduino库函数,用于设置计时器中断 延迟而不是中断的另一种替代方法是设置计时器,并在每次循环中检查它。解释概念。Metro库实现了这一点,并且易于使用。我用它代替了delay(),这样我可以在我的机器人移动时检查按钮是否按下
// 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;
}