Arduino,在for循环中破坏步进电机

Arduino, Breaking Stepper motor in the for loop

需要在"for loop"内中断步进电机运行。但是我写的代码在循环完成后中断操作,它不会中断循环之间的操作。请检查代码并告诉我任何可能的方法来停止两者之间的循环..

代码:

#include <Stepper.h>
int in1Pin = 8;
int in2Pin = 9;
int in3Pin = 10;
int in4Pin = 12;

bool entry = false;
int j;

Stepper motor(200, in1Pin, in2Pin, in3Pin, in4Pin);

void setup() {
  pinMode(in1Pin, OUTPUT);
  pinMode(in2Pin, OUTPUT);
  pinMode(in3Pin, OUTPUT);
  pinMode(in4Pin, OUTPUT);

  while (!Serial);
  Serial.begin(9600);
  motor.setSpeed(300);
  Serial.println("Type in your selection");
  entry = false;
}

void loop() {
  if (Serial.available() > 0){
    switch(Serial.read()){
      case 'a':
       entry = true;
       break;
      case 'b':
       entry = false;
       break;
      default:break;
    }
  }
  if(entry == true){
        for(j = -20; j <= 20; j++){
          motor.step(j/0.176);
        }
      }
  else if(entry == false){
       digitalWrite(in1Pin,LOW);
       digitalWrite(in2Pin,LOW);
       digitalWrite(in3Pin,LOW);
       digitalWrite(in4Pin,LOW);
  }

}

来自评论: 当我通过串行监视器发送 'a' 时,步进器开始旋转,当我通过串行发送 'b' 时,它应该会损坏步进电机旋转,但仅在循环完成后才中断(不在循环内)

如果您不给 Arduino 机会在执行 [=11] 期间解析 串行输入 =] 循环,那么显然不会如你所愿地工作。

你应该做类似的事情:

...

void loop() {
  static int j;

  if (Serial.available() > 0){
    switch(Serial.read()){
      case 'a':
       entry = true;

       /**
        * replace next 3 lines with `j = -20` if you want to start
        * the loop from scratch each time `a` is received,
        * instead of resuming from where you stopped.
        */
       if (j >= 20) {
         j = -20;
       }

       break;
      case 'b':
       entry = false;
       break;
      default:break;
    }
  }

  if (entry) {
    if (j <= 20) {
      motor.step(j/0.176);
      ++j;
    }
  } else {
     digitalWrite(in1Pin, LOW);
     digitalWrite(in2Pin, LOW);
     digitalWrite(in3Pin, LOW);
     digitalWrite(in4Pin, LOW);
  }
}

在这段代码中,我让 Arduino 在每次调用 motor.step() 后解析一个新字符。请注意,此方法在对 motor.step() wrt 的后续调用中引入了 tiny 延迟。你原来的解决方案,但在实践中应该可以忽略不计

如果你使用这段代码连续发送多个aArduino,但是Arduino没有完成for 循环,然后使用此代码附加的 a 将被忽略。如果你想将它们作为额外的 for 请求来处理,那么你应该添加一个 counter 来跟踪你想要执行的 for 循环的待处理(完整)迭代次数.