首页 > 解决方案 > C#中指令之间的精确计时

问题描述

我正在尝试用 C# 重写一些我已经为 Arduino 编写的代码,以便在 Raspberry Pi 3(Windows 10 IOT)上使用。我遇到问题的 Arduino 代码如下:

void loop()
{
    while(true)
    {
        Step();
        delay(100);
    }
}

void Step()
{
    digitalWrite(StepPin, HIGH); //Sets the output to HIGH
    delayMicroseconds(2000);     //Waits 2ms
    digitalWrite(StepPin, LOW);  //Sets the output to LOW
}

这是使用 A4988 步进驱动器控制步进电机的代码。代码目标是每 100 毫秒给驱动板一个 2 毫秒的脉冲。

到目前为止,我在 C# 中所做的是:

public void Runner()
{
    while(true)
    {
        Step();

        //100ms delay here
    }
}    

public void Step()
{
    StepPin.Write(GpioPinValue.High);
    //2ms delay here
    StepPin.Write(GpioPinValue.Low);
}

我试过 Thread.Sleep() 但它似乎不合适,而且这似乎也不是更好:

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
while(stopwatch.ElapsedMilliseconds < 2) ;

实现这种延迟的最佳方式是什么?

标签: c#raspberry-pitimingwindowsiot

解决方案


推荐阅读