So I found this code already available and works fine but when I decrease the sampling window to 0.25ms, the serial monitor is not able to identify any sound and keeps showing the same value always. I have tried changing the millis() to micros() and have also tried quite a few values of signalmin but it does not help. Any idea what has to be done for this small sampling window ? The microphone I am using is czn-15e.
const int sampleWindow = 10; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
void setup()
{
Serial.begin(9600);
}
void loop()
{
unsigned long startMillis= millis(); // Start of sample window
unsigned int peakToPeak = 0; // peak-to-peak level
unsigned int signalMax = 0;
unsigned int signalMin = 1024;
// collect data for 1000 mS
while (millis() - startMillis < sampleWindow)
{
sample = analogRead(0);
if (sample < 1024) // toss out spurious readings
{
if (sample > signalMax)
{
signalMax = sample; // save just the max levels
}
else if (sample < signalMin)
{
signalMin = sample; // save just the min levels
}
}
}
peakToPeak = signalMax - signalMin; // max - min = peak-peak amplitude
double volts = (peakToPeak * 5.0) / 1024; // convert to volts
Serial.println(volts);
}
`
-
\$\begingroup\$ Welcome to EE.SE. Please edit your post. There's a code button on the editor to format your code properly. Capitalise words properly for legibility. In any case, it may be a question for arduino.stackexchange. \$\endgroup\$Transistor– Transistor2017年06月14日 12:25:17 +00:00Commented Jun 14, 2017 at 12:25
1 Answer 1
A quick google indicates that the maximum sample rate on an arduino is around 9.6 kHz. So you're going to get 2 or 3 sample per measurement. Realistically you need several ms to get a meaningful range, the idea of calculating a peak to peak range on a handful of samples just doesn't make sense.
I'm not sure why you don't get a number out when you use micros() but even if it did give a number it wouldn't have a lot of meaning.
Either you need to use something that can sample far faster or you need to re-evaluate what you are trying to do and see if there is a better way to achieve your requirements.
-
\$\begingroup\$ Hmm. My quick look around suggested that Arduinos can call AnalogRead at about 10000 times a second. \$\endgroup\$JRE– JRE2017年06月14日 14:45:32 +00:00Commented Jun 14, 2017 at 14:45
-
\$\begingroup\$ My bad, somehow I mentally missed a digit, it is just under 10kHz. Plus a small overhead for the comparisons and loop but that will be small in comparison to the ~1500 clock cycles the ADC takes. I'll update the answer. \$\endgroup\$Andrew– Andrew2017年06月14日 15:28:32 +00:00Commented Jun 14, 2017 at 15:28