fft_implementation_draft1

Dependencies:   mbed

main.cpp

Committer:
parthchandak02
Date:
2018-03-07
Revision:
0:b723ff6df537
Child:
1:b86b60ae81af

File content as of revision 0:b723ff6df537:

#include <mbed.h>

#include <iostream>
#include <complex>
#define MAX 2048
#define M_PI 3.1415926535897932384

using namespace std;


float s;
float a = 1; //amplitude
float pi = 3.142; //pi
float o = 1/2; //offset
float time_count = 0;

int i = 0; //iteration counter
int f1 = 100; //frequency in Hz
//int f2 = 250; //frequency in Hz
//int f3 = 500; //frequency in Hz
float step = 1/(5*f1);
float time[MAX] = 0;

float* generateTimeVector (float* timeVec, int vecSize, float stepSize)
{
    for(int i=1; i<=vecSize; i++)
    {
        timeVec[i] = i*stepSize;
    }
    return timeVec;  
}

bool set1 = false;
bool set2 = false;
bool set3 = false;

void sineVector (complex<double>* sineVector, int i, int freqHz, int amplitude, int offset);

int log2(int N)    /*function to calculate the log2(.) of int numbers*/
{
  int k = N, i = 0;
  while(k) {
    k >>= 1;
    i++;
  }
  return i - 1;
}

int check(int n)    //checking if the number of element is a power of 2
{
  return n > 0 && (n & (n - 1)) == 0;
}

int reverse(int N, int n)    //calculating revers number
{
  int j, p = 0;
  for(j = 1; j <= log2(N); j++) {
    if(n & (1 << (log2(N) - j)))
      p |= 1 << (j - 1);
  }
  return p;
}

void ordina(complex<double>* f1, int N) //using the reverse order in the array
{
  complex<double> f2[MAX];
  for(int i = 0; i < N; i++)
    f2[i] = f1[reverse(N, i)];
  for(int j = 0; j < N; j++)
    f1[j] = f2[j];
}

void transform(complex<double>* f, int N) //
{
  ordina(f, N);    //first: reverse order
  complex<double> *W;
  W = (complex<double> *)malloc(N / 2 * sizeof(complex<double>));
  W[1] = polar(1., -2. * M_PI / N);
  W[0] = 1;
  for(int i = 2; i < N / 2; i++)
    W[i] = pow(W[1], i);
  int n = 1;
  int a = N / 2;
  for(int j = 0; j < log2(N); j++) {
    for(int i = 0; i < N; i++) {
      if(!(i & n)) {
        complex<double> temp = f[i];
        complex<double> Temp = W[(i * a) % (n * a)] * f[i + n];
        f[i] = temp + Temp;
        f[i + n] = temp - Temp;
      }
    }
    n *= 2;
    a = a / 2;
  }
}

void FFT(complex<double>* f, int N, double d)
{
  transform(f, N);
  for(int i = 0; i < N; i++)
    f[i] *= d; //multiplying by step
}

int main()
{
  complex<double> vec[MAX];
  for (i = 0; i < MAX; i++)
  {
      sineVector(vec, i, f1, a, 0);
  }
  
  FFT(vec, MAX, 1); //'d' should be 1 in order to have the same results of matlab fft(.)
  cout << "...printing the FFT of the array specified" << endl;
  for(int j = 0; j < MAX; j++)
  {
     cout << vec[j] << endl; 
  }
    
  return 0;
}


void sineVector (complex<double>* sineVector, int i, int freqHz, int amplitude, int offset)
{
       sineVector[i] = offset + amplitude*sin((pi/180) * freqHz * i);
}