首页 > 解决方案 > Arduino Autonmous 汽车 if 语句(超声波)

问题描述

我在为自动驾驶汽车创建 if 语句时遇到了问题。汽车跳过了大部分 if 语句并立即转到 else 语句。传感器给出正确的值。是因为我使用“else if”语句还是其他什么?这辆车应该对周围的环境做出反应,所以我不得不尽可能多地给它一些 if 语句。但相反,它只是在向后退的最后一点等待,左后退和右后退。所以我的问题是我是否必须添加更多 if 语句,以便它对周围环境做出更好的反应,还是有更多?下面是 if 语句的代码:

  if (sensors[0] >= 50 ) { //if the distance of the front sensor is greater than 50cm, than set Fwd true. Otherwise its false.
    Fwd = true;
  } else {
    Fwd = false;
  }
  delay(50);
  if ((Fwd == true) && (sensors[1] > 50) && (sensors[2] > 50)) {
    fwd();
  } else if ((Fwd == true) && (sensors[1] < 50)) {
    fwdRight();
  } else if ((Fwd == true) && (sensors[2] < 50)) {
    fwdLeft();
  } else if ((Fwd == false) && (sensors[1] < 50) && (sensors[2] < 50)) {
    Stp();
  } else if ((Fwd == false) && (sensors[1] < 50)) {
    bwdRight();
  } else if ((Fwd == false) && sensors[2] < 50) {
    bwdRight();
  } else {
    Stp();
    delay(1000);
    bwd();
    delay(500);
    bwdLeft();
    delay(500);
    bwdRight();
  }

标签: c++if-statementarduino

解决方案


从整理你的代码开始,很明显哪里出了问题。例如,您Fwd通过执行以下操作调用多个检查:

if ((Fwd == true) && ... ) {
    ...
} else if ((Fwd == true) && ... ) {
    ...
} else if ((Fwd == true) && ... ) {
    ... 
} else if ((Fwd == false) && ... ) {
    ...
} else if ((Fwd == false) && ... ) {
    ...
}

这会占用程序内存中的宝贵资源。进行一次检查并从那里进行评估会更有效率:

if (Fwd){
    // Check sensor conditions here
} else {
    // Check more sensor conditions here
}

事实上,您可以完全省略该Fwd变量(除非您在其他地方使用它),从而节省更多内存空间:

// Check whether to go forward or backwards.
// >= 50 - forward
// <  50 - backward
if (sensors[0] >= 50) {
    // Check sensor conditions here 
} else {
    // Check more sensor conditions here
}

总体而言,您最终可能会得到以下结果:

// Check whether to go forward or backwards.
// >= 50 - forward
// <  50 - backward
if (sensors[0] >= 50) {
    // Going forward, but which direction?
    if (sensors[1] < 50) {
        fwdRight();
    } else if (sensors[2] < 50) {
        fwdLeft();
    } else {
        // sensors[1] >= 50 AND sensors[2] >= 50
        // Going straight forward
        fwd();
    }
} else {
    // Check backward sensor conditions here
}

这个答案可能不会直接回答您的问题,但它应该可以帮助您更好地诊断正在发生的事情。


推荐阅读