【问题标题】:Why is my nested while loop not working?为什么我的嵌套 while 循环不起作用?
【发布时间】:2017-04-14 15:13:59
【问题描述】:

我目前正在 RobotC 中为 Vex 2.0 Cortex 编程。我正在使用编码器让我的机器人直行。

这是我的代码:

void goforwards(int time)
{
    int Tcount = 0;
    int speed1 = 40;
    int speed2 = 40;
    int difference = 10;


    motor[LM] = speed1;
    motor[RM] = speed2;
    while (Tcount < time)
    {
        nMotorEncoder[RM] = 0;
        nMotorEncoder[LM] = 0;

        while(nMotorEncoder[RM]<1000)
        {
            int REncoder = -nMotorEncoder[RM];
            int LEncoder = -nMotorEncoder[LM];

            if (LEncoder > REncoder)
            {
                motor[LM] = speed1 - difference;
                motor[RM] = speed2 + difference;
                if (motor[RM]<= 0)
                {
                    motor[RM] = 40;
                    motor[LM] = 40;
                }
            }
            if (LEncoder < REncoder)
            {
                motor[LM] = speed1 + difference;
                motor[RM] = speed2 - difference;
                if (motor[RM]<= 0)
                {
                    motor[RM] = 40;
                    motor[LM] = 40;
                }
                Tcount ++;
            }
        }
    }
}


task main()
{

    goforwards(10);
}

作为参考,这些是我的 Pragma 设置:

#pragma config(I2C_Usage, I2C1, i2cSensors)
#pragma config(Sensor, dgtl2,  ,               sensorDigitalIn)
#pragma config(Sensor, dgtl7,  ,               sensorDigitalOut)
#pragma config(Sensor, I2C_1,  ,               sensorQuadEncoderOnI2CPort,    , AutoAssign )
#pragma config(Sensor, I2C_2,  ,               sensorQuadEncoderOnI2CPort,    , AutoAssign )
#pragma config(Motor,  port1,           RM,            tmotorVex393_HBridge, openLoop, reversed, encoderPort, I2C_2)
#pragma config(Motor,  port10,          LM,            tmotorVex393_HBridge, openLoop, encoderPort, I2C_1)

当我执行代码时,机器人的编码器值非常接近,但是当它们达到 1000 时机器人停止移动。我认为我编写的代码应该在编码器的值达到 1000 后将其返回为 0,并且因此代码应该在 shell 循环中重复 10 次(在这种情况下)。我做错了什么?

【问题讨论】:

  • RobotC 不是 C

标签: while-loop nested-loops robotics robotc


【解决方案1】:

您在错误的位置更新Tcount。就在外循环的末尾做。

您现在写的内容使Tcount 每次向前移动都会增加。当它达到 1000 步时,Tcount 已经是 1000。

你的times 是 10。所以 `Tcount >= time 并且它不会再次进入外部 while 循环。

【讨论】:

    【解决方案2】:

    似乎内循环的控制变量(即 nMotorEncoder[RM])从未更新,这意味着内循环将永远迭代。也就是说,你永远不会回到外部循环的主体

    【讨论】:

      猜你喜欢
      • 2020-02-10
      • 2016-04-02
      • 1970-01-01
      • 2022-01-26
      • 2022-12-12
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多