Help with coding sound sensor

good morning , I'm working on an arduino project that print sound frequency from a sound sensor ky-037 .I have this code but it seems like something went wrong cause while testing I always figure out that the monitor does not print correct values .If someone could help please I would be so thankfull . This is the code :

' long microSecs;
long freq;
int lastBit;
int nowVal;
long secs;
long maxHz;
long minHz;
long minmax;
void setup() {

microSecs = micros();
freq = 0;
lastBit = 0;
nowVal =0;
maxHz=0;
minHz=0;
minmax=0;
secs = millis();
Serial.begin(9600);
}

void loop() {

if ((microSecs)<micros()){
nowVal=analogRead(A0);

  if (lastBit!=nowVal) {
    lastBit=nowVal;
    freq=freq+1;
  }
  if (freq>maxHz){
    maxHz=freq;
  }
  if (freq<minHz){
    minHz=freq;
  }
  //lcd.clear();
  //lcd.print();
  microSecs = micros();

}
if (secs+1000<millis()){

if (minmax+600000<millis())
{
  minmax=millis();
  minHz=freq;
  maxHz=freq;
  
}
  
 
  Serial.print((freq/2));
 Serial.println(" hz");

  freq=0;
  secs=millis();

}

}'

I don't think you understand what this sensor does. It takes a sound wave and your Arduino should take samples of this ever changing electrical signal.

The data the analogue output of this sensor is not frequencies but simple voltage levels. To convert these levels into frequencies you need to do some complex maths on a succession of these samples.

Most people use an FFT transform Fast Fourier transform - Wikipedia

Fortunately there are FFT libraries which make this much easer to play with.

So do a search for
FFT on an Arduino.

You are making mistakes in how you post your code.
You may want to read this before you proceed:-
how to get the best out of this forum

I don't understand your algorithm, but...

As you may know, all real world sounds contain multiple simultaneous frequencies. If you're trying to make something like a guitar tuner, the "rumor is" autocorrelation works better than FFT. But. I don't know if there are autocorrelation libraries for the Arduino or if that's something you have to figure-out on your own.

Audacity has Analyze -> Plot Spectrum if you want to look at the frequency spectrum of a recorded sound. It's often helpful to know what you're dealing with.

Audacity can also generate "pure tones" which might be helpful during testing/troubleshooting.

You might get "good enough" results by timing between the zero-crossings. You'll probably have to average-out several cycles, and you'll probably need to throw-out the outliers. But note most sound sensors put-out a biased signal (because the Arduino can't read negative) so you'd have to subtract-out the bias (which is about 512 with the standard 10-bit ADC).

P.S.
If you are new to digital audio the Audacity Website has a nice-easy introduction. But they don't cover frequency analysis... That's advanced DSP stuff!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.