0

I'm trying to rewrite some code I already have for Arduino in C# for use on the Raspberry Pi 3 (Windows 10 IOT). The Arduino code is I'm having trouble with is the following:

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
}

This is code is to control a stepper motor using an A4988 stepper driver. The code objective is to give the driver board a pulse of 2ms every 100ms.

What I've done in C# so far is this:

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

        //100ms delay here
    }
}    

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

I've tried Thread.Sleep() but it doesn't seem appropriate and also this doesn't seem better:

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

What would the optimal way to implement this kind of delay be?

prenone
  • 302
  • 2
  • 20
  • Have you looked at the [`Timer`](https://learn.microsoft.com/en-us/dotnet/standard/threading/timers) class? – Heretic Monkey Apr 29 '19 at 19:58
  • Would that have enough precision. I recall reading that it had somewhere around 10ms precision – prenone Apr 29 '19 at 20:03
  • If you want better than millisecond precision, why are you reading the `ElapsedMilliseconds` property and not `ElapsedTicks`? Can you explain why you chose to read the low-resolution version of the property? – Eric Lippert Apr 29 '19 at 20:37
  • The `Timer` class typically has precision on the order of the thread quantum of the operating system. How much "wall clock time" that is depends on details of the operating system and hardware, but yes, it is typically on the order of 8-16 milliseconds. – Eric Lippert Apr 29 '19 at 20:40
  • Thanks for the advice, but how would I about converting the ElapsedTicks to mS, uS or nS? – prenone Apr 29 '19 at 20:41

0 Answers0