我在为自动驾驶汽车创建if语句时遇到了问题。car跳过大多数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();
}发布于 2018-12-12 10:40:15
从整理代码开始,事情可能出错的地方就很明显了。例如,通过执行以下操作调用多个检查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
}这个答案可能不会直接回答你的问题,但它会帮助你更好地诊断正在发生的事情。
https://stackoverflow.com/questions/53739494
复制相似问题