J.Clam
J.Clam

Reputation: 9

Single cycle 44.1kHz sampled 1kHz sine wave in c

I am attempting to create a single cycle sine wave in c. The frequency needs to be approximately 1kHz and sampled at 44.1kHz. This is because the sine lookup table is being fed into a stm32f4 microcontroller that is sampling at 44.1kHz and then out to 5 independent DACs. I have been having issues figuring out how to get exactly 1 cycle of the wave.

Currently I am getting about 10-11 cycles.

for(int j = 0; j < 45; j++){ 
    arr[j] = MAXVOLUME*((sin(2.0*PI*sineFrequency*j/44100.00)+1.0)/2.0);
}

Upvotes: 0

Views: 1195

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126418

Your divisor is wrong -- you want to divide by the number of samples, not by the sampling frequency. Which bring up the problem -- to have exactly one cycle of 1KHz sampled at 44.1KHz, you need 44.1 samples, which is not a round number. So you have two choices:

  • use more samples to get more cycles -- for example, 441 samples would get you 10 cycles at 1 KHz

    for(int j = 0; j < 441; j++)
        arr[j] = MAXVOLUME*((sin(2.0*PI*j/44.1)+1.0)/2.0);
    
  • adjust your desired frequency to match the output frequency -- for example 44 samples for 1 cycle would give you 1.00227KHz when output at 44.1KHz

    for(int j = 0; j < 44; j++)
        arr[j] = MAXVOLUME*((sin(2.0*PI*j/44.0)+1.0)/2.0);
    

Upvotes: 2

Related Questions