2

背景(可以跳到下面的问题...)

目前正在使用乐高 Mindstorm 机器人和 icommand API (http://lejos.sourceforge.net/p_technologies/nxt/icommand/api/index.html)。

其中一种电机控制方法有问题。这些方法将电机旋转给定角度:

Motor.A.rotateTo(target);

在电机完成运动之前,此功能不会返回。这很好,但有时电机无法停止并将无限期地继续,从而停止程序。

问题

无论如何我可以使程序等待n秒以使方法Motor.A.rotateTo(target); 返回。然后如果在那段时间内没有返回,则再次调用该方法。(如果可以循环直到成功,那就更好了。)

感谢您的阅读,任何帮助将不胜感激。

问候,乔

编辑:更正Motor.A.rotate(target);Motor.A.rotateTo(target);

4

3 回答 3

1

您可以使用ExecutorService或其他线程解决方案rotate在单独的线程中运行并等待结果。这是一个完整的程序,它也会重试给定的次数:

public static void main(String[] args) throws TimeoutException {
    final ExecutorService pool = Executors.newFixedThreadPool(10);
    runWithRetry(pool, 5);  //run here
}

public static void runWithRetry(final ExecutorService pool, final int retries) throws TimeoutException {
        final Future<?> result = pool.submit(new Runnable() {
            @Override
            public void run() {
                Motor.A.rotate(angle);
            }
        });
        try {
            result.get(1, TimeUnit.SECONDS);  //wait here
        } catch (InterruptedException e) {
            throw new RuntimeException(e.getCause());
        } catch (ExecutionException e) {
            throw new RuntimeException(e.getCause());
        } catch (TimeoutException e) {
            if (retries > 1) {
                runWithRetry(pool, retries - 1);  //retry here
            } else {
                throw e;
        }
    }
}
于 2012-01-18T18:13:18.247 回答
1

怎么样Motor#rotate(long count, boolean returnNow)stop()如果您希望电机在特定时间后停止,您可以调用。

Motor.A.rotate(150, true);
Thread.sleep(3000);
Motor.A.stop();
于 2012-01-18T18:10:09.420 回答
0

类似的东西怎么样:

int desiredPosition = Motor.A.getTachoCount() + ANGLE_TO_TURN;
long timeout = System.currentTimeMillis + MAX_TIME_OUT;
Motor.A.forward();
while (timeout>System.currentTimeMillis && desiredPosition>Motor.A.getTachoCount()); //wait for the motor to reach the desired angle or the timeout to occur
Motor.A.stop();
于 2012-01-18T18:28:00.117 回答