Search code examples
arduinosensors

I cannot understand the reasoning for the math in this code?


This is the code provided by Seead for a simple analoge sound level sensor?

I understand the code but not the reasoning for sampling for 32 reads?

    const int pinAdc = A0;
    
    void setup()
    {
    Serial.begin(115200);
    //Serial.println("Grove - Sound Sensor Test...");
    }
    
    void loop()
    {
    long sum = 0;
    for(int i=0; i<32; i++)
    {
        sum += analogRead(pinAdc);
    }

    sum >>= 5;

    Serial.println(sum);
    delay(10);
    }

Solution

  • It's doing an average over 32 readings.

    Step 1, sum 32 readings.

    Step 2, bit shift right by 5.

    Shifting right is equivalent to dividing by 2. So 2^5 = 32. So it's equivalent of dividing by 32.