3

I am stuck in a situation where I need to generate a defined frequency of some Hz. I have tried multimedia timers and all other stuff available on the internet but so far an infinite loop with some if-else conditions gave me the best results. But the problem in this approach is that it consumes almost all of the cpu leaving no space for other applications to work properly.

I need an algorithm with either generates frequency of some Hz to KHz.

I am using windows plateform with C#.

horgh
  • 17,918
  • 22
  • 68
  • 123
Danish
  • 59
  • 4
  • 1
    Have you looked at the [different timer classes](http://msdn.microsoft.com/en-us/magazine/cc164015.aspx)? – Oded Oct 04 '12 at 14:09
  • Is this something you are looking for? http://stackoverflow.com/questions/203890/creating-sine-or-square-wave-in-c-sharp – tranceporter Oct 04 '12 at 14:10

4 Answers4

3

You can't accurately generate a signal of a fixed frequency on a non-realtime platform. At any moment, a high priority thread from same or other process could block the execution of your thread. E.g. when GC thread kicks in, worker threads will be suspended.

That being said, what is the jitter you are allowed to have and what is the highest frequency you need to support?

Zdeslav Vojkovic
  • 14,391
  • 32
  • 45
2

The way I would approach the problem would be to generate a "sound wave" and output in on the sound card. There are ways to access your sound card from C#, e.g. using XNA. As others have pointed out, using the CPU for that isn't a good approach.

Joh
  • 2,380
  • 20
  • 31
0

Use Thread.Sleep(delay); in your loop

it's reduce processor usage

burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
  • 2
    Using `Thread.Sleep` might not give them a resolution high enough. When calling `Sleep`, it only dictates the minimum amount of time it will sleep, so on a busy system `Thread.Sleep(1)` may sleep for longer than 1ms (which might be longer than the specified Khz anyway). – Matthew Oct 04 '12 at 14:08
  • Thread.sleep is definitely not the way as correctly mentioned by Matthew. I need to generate 1KHz frequency...microsecond timer event with less cpu load would also work for me. – Danish Oct 04 '12 at 15:17
0

As you are generating a timer, You would want to Sleep based on the period of your frequency.

You will have to run your frequency generator in its own thread and call

Thread.Sleep(yourFrequencyPeriodMs);

in each iteration of period.

loopedcode
  • 4,863
  • 1
  • 21
  • 21