关于中断问题
本帖最后由 ilxingyun 于 2014-4-7 20:16 编辑请教给位大神,为什么中断以后出不来了。就停那了,不走了,用的l293d的板子的库文件
#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);
AF_DCMotor motor3(3);
AF_DCMotor motor4(4);
int hw1;
int hw2;
int hw3;
int hw4; //定义红外循迹
int HWin1=31;
int HWin2=32;
int HWin3=33;
int HWin4=34; //定义红外输入引脚
int pbin=2;
void setup()
{
Serial.begin(9600); //set up Serial library at 9600 bps
Serial.println("Motor Go!");
// turn on motor
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
pinMode(HWin1,INPUT);
pinMode(HWin2,INPUT);
pinMode(HWin3,INPUT);
pinMode(HWin4,INPUT);
attachInterrupt(pbin,MeetPerson,LOW); //定义中断
}
void loop()
{
hw1=digitalRead(HWin1);
hw2=digitalRead(HWin2);
hw3=digitalRead(HWin3);
hw4=digitalRead(HWin4);
if(hw1==LOW && hw2==LOW && hw3==LOW && hw4==LOW)
motor_run();
if(hw1==HIGH && hw2==HIGH && hw3==LOW && hw4==LOW||hw1==HIGH && hw2==LOW&&hw3==LOW&&hw4==LOW ||hw1==LOW&&hw2==HIGH&&hw3==LOW&&hw4==LOW)
motor_turnright();
if(hw1==LOW && hw2==LOW && hw3==HIGH && hw4==HIGH||hw1==LOW && hw2==LOW&&hw3==LOW&&hw4==HIGH ||hw1==LOW&&hw2==LOW&&hw3==HIGH&&hw4==LOW)
motor_turnleft();
if(hw1==HIGH && hw3==HIGH && hw2==HIGH && hw4==HIGH)
motor_stop();
}
void motor_run() //直走
{
Serial.println("forward");
motor1.setSpeed(255);
motor2.setSpeed(120);
motor3.setSpeed(120);
motor4.setSpeed(255);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
}
void motor_turnleft() //左转
{
Serial.println("left");
motor1.setSpeed(255);
motor2.setSpeed(160);
motor3.setSpeed(160);
motor4.setSpeed(255);
motor1.run(FORWARD);
motor2.run(FORWARD);
motor3.run(BACKWARD);
motor4.run(BACKWARD);
delay(500);
motor3.run(FORWARD);
motor4.run(FORWARD);
}
void motor_turnright() //右转
{
Serial.println("right");
motor1.setSpeed(255);
motor2.setSpeed(160);
motor3.setSpeed(160);
motor4.setSpeed(255);
motor1.run(BACKWARD);
motor2.run(BACKWARD);
motor3.run(FORWARD);
motor4.run(FORWARD);
delay(500);
motor1.run(FORWARD);
motor2.run(FORWARD);
}
void motor_stop() //停
{
Serial.println("stop");
motor1.run(RELEASE);
motor2.run(RELEASE);
motor3.run(RELEASE);
motor4.run(RELEASE);
}
void MeetPerson()
{
motor_stop();
} 本帖最后由 Super169 于 2014-4-4 10:15 编辑
Arduino 並不支援 multi-thread 的, 而且 interrupt 內亦不應做太多事情, 特別要注意它跟當前工作的影響.它會把當前執行中的工作暫停, 先執行了 interrupt 的事再執行.如果有些工作在 interrupt 及 loop 的程序有互相衝突的話, 當執行完 interrupt 程序回到主程序時可能會有問題.而且也會有混亂.
例如當 hw1 - hw4 讀取後, 執行 interrupt, 之後回到主程序, 會如何?又或者在 motor action 中途執行 interrupt, 又有什麼事發生?這些都要考慮的.
簡單一點, 可以在 interrupt 程序內只設定一個變數 (例如 motor_stop = 1) , 在 loop 之內 或每一個動作之前 再檢查該變數決定是否停止.這樣的話, 當前執行的動作會先完成, 在下一個動作時才停止, 就會清楚及安全得多了.只是不能即時停下來.如要把當前的執行中的動作也即時停下來, 就要更複雜一點了, 又或者每一句執行動作都檢查一下該變數.但也要考慮實際是否可行.
Super169 发表于 2014-4-4 10:10 static/image/common/back.gif
Arduino 並不支援 multi-thread 的, 而且 interrupt 內亦不應做太多事情, 特別要注意它跟當前工作的影響. ...
哦哦~长知识了!非常感谢。另外想问一下您板子的数字接口初始是高电平还是低电平?
页:
[1]