Thursday, December 31, 2015

Sine wave generating in C

The code in the  below can generate a sine wave which is summing of 3 different signal.
Frequency and amplitudes of these signals are selectable.
Also you can modify c file with small changes as desired.
f1,f2,f3      => Frequencies
A1,A2,A3 => Amplitudes
I wrote generated sine wave a .txt file :)
* The code compiled and tested in Dev-C++ 5.11 TDM-GCC.





 #include <stdio.h>  
 #include <stdlib.h>  
 #include <math.h>  
 #include <complex.h>  
 float pinum;  
 typedef double complex comp;  
 int main(void)  
 {  
  FILE *sin_tab_r;  
  sin_tab_r = fopen("sin_tab_r.txt","w+") ;  
  FILE *sin_tab_i;  
  sin_tab_i = fopen("sin_tab_i.txt","w+") ;  
  pinum = atan2(1.0,1.0) * 4 ;  // pi : about 3.14
  int Fs = 100000000; // Sampling Rate(Hz)  
  int L;  // Size of wave
  double time_interval = (double)1/Fs; //Sampling Period.. i.e. 1ms  
  int len = 1024;  
  int f1 = 6250000;  
  int f2 = 12500000;  
  int f3 = 25000000; // sine frequencies  
  int A1 = 500;  
  int A2 = 700;  
  int A3 = 200;  //sine amplitudes
  comp sin_arr[len];  
  for(L=0;L<len;L++)  
  {  
    // discrete: sin(n) = 2*pi*f*n*ts  
    sin_arr[L] = ((A1 * sin(2.0 * pinum * f1 * L * time_interval )) + (A2 * sin(2.0 * pinum * f3 * L * time_interval )) + (A3 * sin(2.0 * pinum * f2 * L * time_interval )));  
    // withot comma  
    //fprintf(sin_tab_r,"%g\n",round(creal(sin_arr[L])));  
    // with comma  
    fprintf(sin_tab_r,"%s%g\n",",",round(creal(sin_arr[L])));  
    // imag  
    fprintf(sin_tab_i,"%d\n",0);  
  }    
 }  

No comments:

Post a Comment