使用 RobotC 进行 MindstormsNXT 编程时遇到问题

问题描述 投票:0回答:1

我在使用 RobotC 控制我的 Mindstorms NXT 机器人时遇到问题。我希望我的机器人能够在桌子上向前移动,当到达末端时,面朝下的超声波传感器将通过观察地面的距离来确定它是否位于边缘。当超声波传感器发现处于边缘时,机器人会从边缘向后移动,掉头,朝另一条路走。

这是我的代码:

#pragma config(Sensor, S1,     ,               sensorSONAR)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

task main()

{

int Ultrasonic; 
Ultrasonic = SensorValue[S1];

while (true)
{
    if (Ultrasonic >10)
{
motor[motorB] = -100;
motor[motorC] = -100;
wait1Msec(2000);

motor[motorB] = 100;
wait1Msec(2000);
}
if (Ultrasonic <= 10)
{
    motor[motorB] = 50;
    motor[motorC] = 50;
    wait1Msec(5000);
}
}
}
c robotics lego-mindstorms nxt
1个回答
1
投票

这个程序的问题是你实际上只从超声波传感器读取一次。这是运行程序时会发生的情况:

  1. 创建变量
    Ultrasonic
    ,并将传感器值分配给它。
  2. 程序检查超声波传感器的值。
  3. 程序根据超声波传感器读取的内容执行某些操作。
  4. 程序根据超声波传感器读取的内容执行某些操作。

...

要解决这个问题,您需要做的就是将超声波传感器的读数移入

while
循环中,以便NXT不断检查传感器的值。修改后的版本如下所示:

task main()
{
    int Ultrasonic; 

    while (true)
    {
        Ultrasonic = SensorValue[S1];
        if (Ultrasonic > 10)
        {
            // ... Do stuff here...
        }
        if (Ultrasonic <= 10)
        {
            // ... Do more stuff here...
        }
    }
}

事实上,您可以通过使用“if...else...”语句结合对超声波传感器值的检查,使此代码更加“干净”。它会检查一个值,然后根据该值是否为真做出决定。只需将行

if (Ultrasonic <= 10)
替换为
else

© www.soinside.com 2019 - 2024. All rights reserved.