Generate a square waveform in C?
How to generate an efficie开发者_运维技巧nt square waveform with varying duty cycle using C language?
Choose your output format. Headerless PCM is probably best to start with. Select your output format - say, 16 bit stereo at 44 KHz. Choose your endianness. Write a bit of code which emits to a file logical 0 for 1 seconds worth of data; then emits logical 65535 for one second worth of data. Repeat.
That file contains your waveform.
Let N be the cycle length (1 / frequency). N is a count of some small quanta, like clock ticks. Let D be the amount of quanta the output is high during each cycle of N. The algorithm is trivial:
loop indefinitely:
for D ticks:
output 1
for N - D ticks:
output 0
精彩评论