Hello, I am trying to attach a push button to my frequency detection code. I want it to where when the button is pressed and held, the microphone will start reading values and stop when the button is let go. I tried add that to the code but no luck. I dont get any readings when i push the button.
Can someone look over my code.
#define LENGTH 512
byte rawData[LENGTH];
int count;
//Sample Frequency in kHz
const float sample_freq = 2400;
const byte buttonPin = 9;
const byte microphone = A0;
int len = sizeof(rawData);
int i,k;
long sum, sum_old;
int thresh = 0;
float freq_per = 0;
byte pd_state = 0;
bool
bMeasureEnable;
byte
buttonState,
lastButtonState;
void setup(){
pinMode(microphone, OUTPUT);
pinMode(buttonPin, INPUT);
lastButtonState = digitalRead( buttonPin );
bMeasureEnable = false;
analogRead(A0);
Serial.begin(115200);
count = 0;
}
void loop(){
ReadButton();
MeasureFrequency();
}//loop
void ReadButton( void )
{
static unsigned long
timeRead = 0;
if( millis() - timeRead < 30 )
return;
timeRead = millis();
buttonState = digitalRead(buttonPin);
if( buttonState != lastButtonState )
{
lastButtonState = buttonState;
if( buttonState == HIGH )
bMeasureEnable = true;
else
bMeasureEnable = false;
}//if
}//ReadButton
void MeasureFrequency( void )
{
static unsigned long
timeMeasure = 0;
float
freq;
if( millis() - timeMeasure < 1000 )
return;
timeMeasure = millis();
if( !bMeasureEnable )
return;
if (count < LENGTH) {
count++;
rawData[count] = analogRead(A0)>>2;
}
else {
sum = 0;
pd_state = 0;
int period = 0;
for(i=0; i < len; i++)
{
// Autocorrelation
sum_old = sum;
sum = 0;
for(k=0; k < len-i; k++) sum += (rawData[k]-128)*(rawData[k+i]-128)/256;
// Serial.println(sum);
if (pd_state == 2 && (sum-sum_old) <=0)
{
period = i;
pd_state = 3;
}
if (pd_state == 1 && (sum > thresh) && (sum-sum_old) > 0) pd_state = 2;
if (!i) {
thresh = sum * 0.5;
pd_state = 1;
}
}
// for(i=0; i < len; i++) Serial.println(rawData[i]);
// Frequency identified in Hz
if (thresh >100) {
freq_per = sample_freq/period;
Serial.println(freq_per);
}
count = 0;
}
}