title: Trouble Generating a Sine Wave in C/Matlab from Basics
body: <p>I've been writing a basic C program to generate a sine wave and write it out to STDOUT for piping into a filter which I am also going to write but I'm having issues.</p>
  
  <p>I am able to generate what sounds like a good clean sine wave, but the frequency is off.  When I listen to the output I am generating and compare to a true signal generators output, the frequency of mine is slightly too high.</p>
  
  <p>The C code should generate raw 16 bit signed stereo wav @ 44100Hz for a frequency passed as an argument to the program, or 500Hz as default.</p>
  
  <p>A matlab version of the code is here, (modded very slightly for 1 indexing in Matlab, WHY MATHWORKS WHY!?) minus the passing to STDOUT etc as I know that works fine</p>
  
  <pre><code>CHANNELS = 2; SAMPLING_RATE = 44100; NUM_SAMPLES = 512;
  
  frequency = 1000;
  
  %% BEGIN WHILE(1) LOOP HERE
  
  output_buff = zeros(1,CHANNELS*NUM_SAMPLES);
  
  for i = 1:2:CHANNELS*NUM_SAMPLES
      output_buff(i) = 30000 * sin(frequency * pi * (i-1)/NUM_SAMPLES);
      output_buff(i+1) = output_buff(i);
  end
  
  %% OUTPUT TO STDOUT AND REPEAT
  </code></pre>
  
  <p>I should add that this code runs (in the C version) inside a while true loop, generating a full output_buff of values, then pushing the buffer to STDOUT.</p>
  
  <p>I have written some further testing code to see what's actually being generated as follows:</p>
  
  <pre><code>plot(1:CHANNELS*NUM_SAMPLES, output_buff)
  
  output_buff = output_buff .* hanning(length(output_buff))';    
  Y = fft(output_buff);    
  Mag=abs(Y(1:length(output_buff)/2)).^2;    
  [a,b]=max(Mag);    
  % Result    
  SAMPLING_RATE*b/length(output_buff)
  </code></pre>
  
  <p>When I run this script, I can see at the end the frequency of the generated signal is actually 1.0767e+03Hz... Close but no cigar...</p>
  
  <p>I've tried tweaking some of the parameters but I have no idea what's wrong or how to make the generated frequency more accurate.</p>
  
  <p>The C code itself is on my Linux install and I can add that tomorrow if needs be.</p>