0

我需要监控旋转编码器的位置来控制直流电机。为了确保我不会错过我使用了 BackgroundWorker 的旋转编码器中的更改。

我的应用程序没有按预期工作,所以我正在调试以查看为什么它经常错过标记。

使用 Console.WriteLine 我正在写出秒表的状态,我注意到线程正在“跳过”或缺少循环,这可能是写出控制台的怪癖吗?

这是输出的一小部分,您可以看到有 190ms 的间隙:

Inside Thread. Time: 25, Position: 117, Velocity: 0
Inside Thread. Time: 26, Position: 117, Velocity: 0
Inside Thread. Time: 27, Position: 117, Velocity: 0
Inside Thread. Time: 28, Position: 117, Velocity: 0
Inside Thread. Time: 29, Position: 117, Velocity: 0
Inside Thread. Time: 30, Position: 117, Velocity: 0
Inside Thread. Time: 212, Position: 117, Velocity: 0
Inside Thread. Time: 213, Position: 117, Velocity: 0
Inside Thread. Time: 214, Position: 117, Velocity: 0
Inside Thread. Time: 215, Position: 117, Velocity: 0
Inside Thread. Time: 216, Position: 117, Velocity: 0
Inside Thread. Time: 217, Position: 117, Velocity: 0

这是我在后台工作程序中运行的代码(请注意,它目前只是在我调试时写入控制台,工作时它将控制直流电机):

    public void dcMotorMove(DCMotorSettings dcMotorSettings)
    {
        try
        {
            dcMotorSettings.Moving = true;

            Stopwatch dcMotorStopwatch = Stopwatch.StartNew();
            dcMotorStopwatch.Restart();

            int MoveState = 1;

            while (MoveState != 0)
            {
                Console.WriteLine("Inside Thread. Time: " + dcMotorStopwatch.ElapsedMilliseconds + ", Position: " + dcMotorControl.encoders[0].Position + ", Velocity: " + dcMotorControl.motors[0].Velocity);

                Thread.Sleep(dcMotorSettings.SampleRate); // Processor Rest
                if (dcMotorStopwatch.ElapsedMilliseconds > dcMotorSettings.Duration)  MoveState = 0;

            }

            dcMotorSettings.Moving = false;
        }
        catch
        {
            Console.WriteLine("Problem within dcMotorMove");
        }
    }
4

3 回答 3

2

我不认为这里有错误。没有办法在虚拟平台 (.NET) 而不是实时操作系统上组织代码的时间精确执行。秒表本身只提供测量时间间隔的机会。您的特定情况取决于数百万个因素(例如系统中运行的当前进程、内存量等)

于 2012-02-08T23:17:08.797 回答
2

课堂上不太可能出现问题Console

我可以看到可能导致这种情况的唯一原因是您转储到控制台 ( Position, Velocity) 的属性可能需要一些时间来评估,这可能是由于您使用的连接限制。

看看你是否可以在没有每秒 1000 个样本的情况下生活,以及你的连接是否可以支持。或者即使您的库确实经常刷新,或者它会向您发送上次读取的缓存值。

于 2012-02-08T23:10:57.360 回答
1

This is not a quirk of the console. Try printing dcMotorSettings.SampleRate as well.

Edit: Try changing the inner loop to:

            Console.WriteLine("Inside Thread. Time: " + dcMotorStopwatch.ElapsedMilliseconds);
            Thread.Sleep(1);

If the effect still happens it is a operating system issue (or too much load on the system). If the effect doesn't happen you comment code in until it does again.

于 2012-02-08T22:51:14.053 回答