I'm working on a software stepper motor controller in C#. The program uses a Measurement Computing PCI-INT32 digital I/O board to output a series of pulses to a stepper motor. The pulses are generated in software. I've tried two methods to achieve this: 1) use a timer control to oscillate and turn the output on and off, or 2) use a while loop with a Thread.Sleep() line to generate delays.
The problem I am having is that it won't generate a proper, fast pulse
train - for example, using Thread.Sleep(1), which should produce a pulse every 1ms actually runs rather eratically at much less than this speed. The alternative method using timers produces very high CPU usage, and a similarly erratic pulse train. Also, for some strange reason the timer refused to let me set its interval property in code (the line pulseTimer.Interval = pulse_length; simply froze the system).
I have also tried a dodgy "hack" method of producing pulses - use a while loop that counts up to, say, 100,000 to generate a delay (rather than Thread.Sleep). This actually produces a much faster pulse train, but I am reluctant to use this method as I obviously have no control over the actual length (in ms) of the delay.
How can I get C# to generate a nice, smooth, accurate pulse train? By the way, I need to use delays of less than 1ms (to achieve an output frequency up to around 4000Hz), but Thread.Sleep() only allows an integer value for delay.