首页 文章

Arduino Autonmous 汽车 if 语句(超声波)

提问于
浏览
0

在为自动驾驶汽车创建 if 语句时遇到了一个问题。汽车会跳过大多数 if 语句,然后立即转到 else 语句。传感器给出正确的值。是因为我使用“ else 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();
  }

1 回答

  • 1

    从整理您的代码开始,很明显哪里出了问题。例如,您通过执行以下操作向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
    }
    

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

相关问题