我需要监控旋转编码器的位置来控制直流电机。为了确保我不会错过我使用了 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");
}
}