I'm in the process of implementing the Goertzel Algorithm in C++, and I've gotten so far:
#include <iostream>
#include <fstream>
#include <string>
#include <math.h>
const double pi = 3.14159;
class digitalFilter{
private:
int k,i;
float temp;
float scalingFactor;
float floatnumSamples;
float omega,sine,cosine,coeff,q0,q1,q2,magnitude,real,imag;
int const static limit = 205;
public:
digitalFilter();
void readDataFromFile();
float goertzel_mag(int numSamples,int TARGET_FREQUENCY,int SAMPLING_RATE, float* data);
};
digitalFilter::digitalFilter(){
float* data = new float[limit];
}
void digitalFilter::readDataFromFile(){
//get 205 values from txt file and store this in an array
std::ifstream dataFile ("data_files/datad.txt");
if (dataFile.is_open()){
for (int i = 0; i < limit; i++){
dataFile >> temp;
data[i] = temp;
}
dataFile.close();
}else{
std::cout << "Unable to open file\n";
}
}
float digitalFilter::goertzel_mag(int numSamples,int TARGET_FREQUENCY,int SAMPLING_RATE, float* data){
scalingFactor = numSamples / 2.0;
floatnumSamples = (float) numSamples;
k = (int) (0.5 + ((floatnumSamples * TARGET_FREQUENCY) / SAMPLING_RATE));
omega = (2.0 * pi * k) / floatnumSamples;
sine = sin(omega);
cosine = cos(omega);
coeff = 2.0 * cosine;
q0=0;
q1=0;
q2=0;
for(int i = 0; i < numSamples; i++)
{
q0 = coeff * q1 - q2 + data[i];
q2 = q1;
q1 = q0;
}
// calculate the real and imaginary results
// scaling appropriately
real = (q1 - q2 * cosine) / scalingFactor;
imag = (q2 * sine) / scalingFactor;
magnitude = sqrtf(real*real + imag*imag);
std::cout << "a" << TARGET_FREQUENCY << " = " << magnitude << std::endl;
return magnitude;
}
int main()
{
digitalFilter ObjOne;
//compute amplitude magnitude of DFT
ObjOne.readDataFromFile();
ObjOne.goertzel_mag(205,697,8000,data);
ObjOne.goertzel_mag(205,770,8000,data);
ObjOne.goertzel_mag(205,852,8000,data);
ObjOne.goertzel_mag(205,941,8000,data);
ObjOne.goertzel_mag(205,1209,8000,data);
ObjOne.goertzel_mag(205,1336,8000,data);
ObjOne.goertzel_mag(205,1477,8000,data);
ObjOne.goertzel_mag(205,1633,8000,data);
return 0;
}
But I get these silly error codes:
goertzel_mag-v3.cpp: In member function 'void digitalFilter::readDataFromFile()':
goertzel_mag-v3.cpp:41:4: error: 'data' was not declared in this scope
goertzel_mag-v3.cpp: In function 'int main()':
goertzel_mag-v3.cpp:85:35: error: 'data' was not declared in this scope
I am utterly and completely lost, why can't my member function readDataFromFile()
find my array data[]
?? It seems like the constructor builds the array and then destroys it after the program leaves the constructor?? How can i fix these apparently silly errors?