c++ - 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();
}
解决方案
从整理你的代码开始,很明显哪里出了问题。例如,您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
}
这个答案可能不会直接回答您的问题,但它应该可以帮助您更好地诊断正在发生的事情。
推荐阅读
- powerbi - powerBI 查找和子字符串
- java - SQSEvent 在 aws-lambda-java-events 1.x 中不存在并且 AmazonS3 在 aws-lambda-java-events 2.x 中不存在?
- r - R中的多个数据帧为空
- php - 从 url 获取 api json 数据
- javascript - 根据点击的元素触发不同的功能
- html - 页脚偏移中的数据表下拉列表
- html - 如何让两个垂直元素的高度之一取决于另一个?
- android - 如何使用 JDBC 驱动器将 MySql 表图像 (BLOB) 加载到 ImageView
- java - 迁移到 java 9 时,反射 API 没有抛出此类方法异常
- python - [Tkinter]当我使用'place'方法放置文本时,我无法将文本插入文本小部件,我也无法编辑它