【问题标题】:Breaking a while loop in Arduino在 Arduino 中打破 while 循环
【发布时间】:2018-05-05 08:09:09
【问题描述】:

我有一个程序可以将步进电机向右、向左移动,并有一个停止电机的停止按钮。在我的程序的一部分中,电机逐渐降低速度并在一段时间后停止iv。 问题是在程序的这一部分(当电机逐渐降低速度然后停止时)我无法在按下停止按钮时停止电机。我知道我需要以某种方式打破 while 循环,但使用 break 语句对我来说没有用。

你有什么想法吗?

这是我的功能:

/* --- STEPPER MOTOR ---*/
const int motor_step = 3;
const int motor_dir = 4;        
int stepSpeed = 0;
int stepMaxSpeed = 1000;        
int fadeAmount = 100;           
int fadeDelay = 10;

/* ---- STOP BUTTON ---- */
int buttonStop = 5;             
int stateStop=0;

void setup() {
  .
  .
  .
  stateStop = digitalRead(buttonStop);
}
void loop () {
  .
  .
  .
  myfunc();
}


void myfunc() {
  if(stateStop == HIGH) {noTone(motor_step); stepSpeed = 0;}

  elapsedMillis te;
  unsigned int iv = 1500;

  while (te < iv) {
     if(stepSpeed == stepMaxSpeed) {
       stepSpeed = stepSpeed+0;
       tone(motor_step,stepSpeed);
       digitalWrite(motor_dir,HIGH); 
     }
     else {
       stepSpeed = stepSpeed + fadeAmount;
       tone(motor_step,stepSpeed);
       digitalWrite(motor_dir,HIGH);
       delay(fadeDelay);
     }
     if(stateStop == HIGH) { stepSpeed = 0; break;}
   }
   if(stepSpeed == stepMaxSpeed) {
     while(stepSpeed>0){
       stepSpeed = stepSpeed-fadeAmount;
       tone(motor_step,stepSpeed);
       digitalWrite(motor_dir,HIGH);
       delay(fadeDelay);
       if(stateStop == HIGH) { stepSpeed = 0; break;}
     }
   }
   stepSpeed = 0;
   noTone(motor_step);
   digitalWrite(enable,LOW); // enable changed from HIGH
}

【问题讨论】:

  • 你有没有考虑过只让while循环中的一个变量结束循环?比如说,将iv(无论那个神秘的名字是什么意思)设置为&lt;te 的名字一样糟糕,比如iv = 0
  • 我投票决定将此问题作为离题结束,因为这是一个 X\Y 问题,无需执行他们要求的操作即可轻松解决。
  • 您的问题是X/Y Problem。告诉我们您要解决什么问题,而不是寻求解决方案的帮助,这似乎不是正确的方法。

标签: while-loop arduino break


【解决方案1】:

您的break 条件永远不会触发,因为stateStop 永远不会在您的while 循环中更新。你的程序应该如何知道?它忙于运行循环,不关心超出其范围的任何内容。

检查while循环内的按钮状态或使用中断

【讨论】:

  • 使用中断不是我的情况,因为应该与中断一起使用的两个引脚已经用于步进电机步进和 dir。但是,我将尝试检查 while 循环内的按钮状态。谢谢
猜你喜欢
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-23
  • 2020-10-21
  • 2012-02-14
  • 2021-12-31
  • 1970-01-01
相关资源
最近更新 更多