Explain please!!!

Hi,

This code is from the adafruit website, named Measuring SPL readings.

It prints the vales from 0 - 1023 but i don’t understand why i dont get any negative values as its a peak to peak output.

Could someone please explain?

/****************************************
Example Sound Level Sketch for the 
Adafruit Microphone Amplifier
****************************************/
 
const int sampleWindow = 50; // 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 50 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) / 1024;  // convert to volts
 
   Serial.println(peakToPeak);
}

Could someone please explain?

How can any value in the range 0 to 5V be negative?

So its not peak-to-peak, its peak?

Is the DC offset 512 then?

Quote from the Article you got the code from:

The output will have a DC bias of VCC/2 so when its perfectly quiet, the voltage will be a steady VCC/2 (1.65v).

So if you power it from 3,3V then with no input you will read 1,65V aka 1,65V / (1024 / 5V) = 337. Max negative peak will be at 0V (that's negative to Vcc/2) aka 0. And the positive peak will be at 3,3V aka 3,3V / (1024 / 5V) = 675.

Im so confused. When i upload it to print volts. it is sitting at 0.23

does the DC bias actually matter?

Have you read the code at all?

   peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude
   double volts = (peakToPeak * 5) / 1024;  // convert to volts

   Serial.println(peakToPeak);

So it does not print what it reads directly but the found peak to peak value. And a peak to peak value is always a positive number because we treat is as a absolute value.

One really wonders what prompted this line!

if (sample < 1024) // toss out spurious readings

A reading of 1024 or higher from a 10 bit ADC would be an impressive achievement…

Someone had a bad day at the Adafruit office... :p