AnalogRead didn't work in setup()

I have some code which is monitoring the noise level in a room. It runs in a Nano, on which one pin is connected to a peak voltage detector from an amplified electret mic. The idea is to determine an average noise level spanning ten seconds, with 20 samples taken at 0.5 second intervals. Once an initial average is computed, it is maintained by always using the last 20 values, continually taken at 0.5 sec. intervals.

So initially, I collected 20 samples in the setup() section and averaged them. I am using DEFAULT analogReference(), and the voltage on the pin being read is 2.1 v. When I compute the initial average in setup(), I get 0.91 v.

So I moved the initial computation to the top of loop(), and now it provides a correct value of 2.1 v. Has anybody else ever seen this anomaly? Perhaps the analogReference() call is somehow not executed until setup() is over.

We need you to help us.
You know the drill. . . . .

I have some code

And after 600 posts, you thought you wouldn't show it to us?

I don't believe the environment provided by setup() is any different to the environment provided by loop() (see below). The effect you describe is likely to be the result of a timing problem.

#include <Arduino.h>

int main(void)
{
    init();

#if defined(USBCON)
    USBDevice.attach();
#endif
   
    setup();
   
    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
       
    return 0;
}

Sorry to be so slow responding -- got very busy.

The code involved is below. I consider the resort of the code is not relevant to this, since the difficulty occurs in setup(), before anything else has run.

I also had to eliminate all variable definitions to get this to fit in a post.

#include <PinChangeInt.h>
#include <EEPROM.h>
#include <Wire.h>
#include <SPI.h>
#include<RH_RF22.h>

RH_RF22 rf22;

void setup() 
{
   int i;
   byte data;
   
   pinMode(shutdownPin, OUTPUT);
   digitalWrite(shutdownPin, HIGH);    //turns on the 5 v. supply

   Serial.begin(57600);
   analogReference(DEFAULT);         //rely on the power supply voltage standard for analog  
   pinMode(sonicPin, INPUT);         //interrupt 0, for microphone input pulses
   pinMode(XBPin, INPUT);            //interrupt 1, for radar input 
   pinMode(radLEDPin, OUTPUT);
   digitalWrite(radLEDPin, LOW);
   pinMode(trainBtnPin, INPUT_PULLUP);
   pinMode(trainLEDPin, OUTPUT);
   digitalWrite(trainLEDPin, LOW);
   pinMode(txLEDPin, OUTPUT);
   digitalWrite(txLEDPin, LOW);
   pinMode(batMonPin, INPUT);
   pinMode(mainsMonPin, INPUT);
   pinMode(peakReadPin, INPUT);
   pinMode(alertPin, OUTPUT);
   digitalWrite(alertPin, LOW);
   pinMode(tempInPin, INPUT);
   
   attachInterrupt(1, int1_ISR, FALLING);   //counts microphone pulses for smoke detector audio detection
   attachPinChangeInterrupt(XBPin, radarCount, RISING);
   
   radioOK = false;  
   if(rf22.init()) radioOK = true; 
   
   //set up timer 2 as a 0.5 ms clock
   
   cli();                         //disable all interrupts
                                  //setting up timer0 for 0.5 ms. (max) cycle
   TCCR2A = 0;                    //clear both timer0 configuration registers: gonna use as a 0.5 msec. timer
   TCCR2B = 0;  
   TCNT2  = 0;                    //set the counter register to 0, and set  
   OCR2A = 125;                   //255x64/16000000 = 0.5 ms.  
   TCCR2A = TCCR2A | B00000010;   //turn on CTC mode
   TCCR2B = B00001100;            //CS1:2:0 to 101 to operate at clock speed/64 
                                  //this also establishes that WGM13:0 = 0100, i.e., CTC mode
   TIMSK2 = TIMSK2 | B00000010;   //enable the CTC interrupt                                                 
   sei();      
     
   data = EEPROM.read(0); 
   if (data != 0b10101010)         //EEPROM address 0 contains this flag if the sytem has been trained
   {
      for(i = 0; i < 3; i++)       //use 3 flashes of radar LED (red) to indicate smoke detector detector is untrained     
      {
         digitalWrite(radLEDPin, HIGH);
         wait(300);
         digitalWrite(radLEDPin, LOW);
         wait(300);
      }
      trained = false;
   }  
   else
   {
      trained = true;
      targetFreq = EEPROM_ReadInt(1);
      Serial.print("SD Freq: "); Serial.println(targetFreq);
      for(i = 0; i < 3; i++)       //use 3 flashes of train LED (yellow) to indicate smoke detector detector is trained     
      {
         digitalWrite(trainLEDPin, HIGH);
         wait(300);
         digitalWrite(trainLEDPin, LOW);
         wait(300);
      }
      minTemp = EEPROM_ReadInt(3);      //pick the temp/humidity limis from EEPROM
      maxTemp = EEPROM_ReadInt(5);
      minHum = EEPROM_ReadInt(7);
      maxHum = EEPROM_ReadInt(9);
    } 
    
    Serial.print("Min. temp. = "); Serial.println(minTemp);
    Serial.print("Max. temp. = "); Serial.println(maxTemp);
    Serial.print("Min. hum. = "); Serial.println(minHum);
    Serial.print("Max. hum. = "); Serial.println(maxHum);
    
    if(radioOK)                //3 flashes of TxLED (blue)  to indicate radio has initialized
    {
      for (i = 0; i < 3; i++)
      {
         digitalWrite(txLEDPin, HIGH);
         wait(300);
         digitalWrite(txLEDPin, LOW);
         wait(200); 
      }
      Serial.println(F("Radio Init OK."));
    }  
    
    digitalWrite(alertPin, HIGH);     //test the beeper
    wait(200);
    digitalWrite(alertPin, LOW);

    
    Serial.print("Determining average noise...");
    bufIndex = 0;
    for(i = 0; i < 20; i++)                                                    //compute an initial value for average noise
    {                                                      //gathering 20 samples over 10 seconds
      data = analogRead(peakReadPin);
      noiseVolts = (float(data)/1023.0)*ARef;
       
      if (bufIndex < 20)
      {
         noiseArray[bufIndex] = noiseVolts;                  //initial filling of buffer
         bufIndex++;
      }  
       
      if (bufIndex == 19)
      {
         avgNoise = 0.0;
         for(i = 0; i < 20; i++)  avgNoise = avgNoise + noiseArray[i]; 
         avgNoise = avgNoise/20;
         noiseStart = true;
         Serial.print(avgNoise); Serial.println(" v.");
      }  
      wait(500);
    }//for i
   
    tempAvg = 0.0;
    humAvg = 0.0;
    cycleCount = avgCount + 1;  //prevents counting until training is over
    nmbrDetects = 0; 
    clockTick = 0;
    secTick = 0;
    minTick = 0;
    sddAlerts = 0;
    notify = false;
    noiseDetects = 0;
    freqData = false;
    freqIndex = 0;
    nextTempRdg = 60000;   //first temp/humidity readingat 30 sec.
    noiseWait = 0;
    later = 0;
    nextTempWarn = 0;
    nextNoise = 2000;      //first noise reading 1 sec.
    noiseStart = false;
    mainsDead = false;
    fireCount = 0;     
 }//setup
 Serial.print("Determining average noise...");
    bufIndex = 0;
    for(i = 0; i < 20; i++)                                                    //compute an initial value for average noise
    {                                                      //gathering 20 samples over 10 seconds
      data = analogRead(peakReadPin);
      noiseVolts = (float(data)/1023.0)*ARef;
       
      if (bufIndex < 20)
      {
         noiseArray[bufIndex] = noiseVolts;                  //initial filling of buffer
         bufIndex++;
      }  
       
      if (bufIndex == 19)
      {
         avgNoise = 0.0;
         for(i = 0; i < 20; i++)  avgNoise = avgNoise + noiseArray[i]; 
         avgNoise = avgNoise/20;
         noiseStart = true;
         Serial.print(avgNoise); Serial.println(" v.");
      }  
      wait(500);

I see two problems in the averaging snippet.

First, because of where bufIndex is incremented, you only load 19 values into the array.

Second, this is wrong. The for loop needs brackets.

 for(i = 0; i < 20; i++)  avgNoise = avgNoise + noiseArray[i];

It should be something like this, with the division after the summation.

for(i = 0; i < 20; i++)
{  
avgNoise = avgNoise + noiseArray[i];
} 
 avgNoise = avgNoise/20;

I would recraft the routine to separate the collection of the data from the averaging. I think is is more simple like this

void setup() {

  Serial.begin(9600);
  Serial.println("Average 20 Analog Reads");
  float noiseArray[20];
  float avgNoise = 0;
  for ( byte i = 0; i < 20; i++)
  {
    Serial.print(i);
    noiseArray[i] = 2.1;//result of analogRead
    delay(500); //wait(500);
  }
  Serial.println();
  for (byte i = 0; i < 20; i++)
  {
    avgNoise = avgNoise + noiseArray[i];
    Serial.println(avgNoise);
  }
  avgNoise = avgNoise / 20.0;
  Serial.println(avgNoise);
}

void loop() {}

Without looking too deeply at your whole code, you are doing something which could make it very error prone and difficult to follow. You are modifying your loop control variable (i in this case) within the loop itself.

    Serial.print("Determining average noise...");
    bufIndex = 0;
    for(i = 0; i < 20; i++)                                                    //compute an initial value for average noise
    {                                                      //gathering 20 samples over 10 seconds
      data = analogRead(peakReadPin);
      noiseVolts = (float(data)/1023.0)*ARef;
      
      if (bufIndex < 20)
      {
         noiseArray[bufIndex] = noiseVolts;                  //initial filling of buffer
         bufIndex++;
      }  
      
      if (bufIndex == 19)
      {
         avgNoise = 0.0;
         for(i = 0; i < 20; i++)  avgNoise = avgNoise + noiseArray[i];
         avgNoise = avgNoise/20;
         noiseStart = true;
         Serial.print(avgNoise); Serial.println(" v.");
      }  
      wait(500);
    }//for i

from what I understand of your code above, it could be simplified to the following:

    Serial.print("Determining average noise...");
    avgNoise = 0.0;
    for(i = 0; i < 20; i++)                                //compute an initial value for average noise
    {                                                      //gathering 20 samples over 10 seconds
      data = analogRead(peakReadPin);
      noiseVolts = (float(data)/1023.0)*ARef;
      noiseArray[bufIndex] = noiseVolts;                  //initial filling of buffer (if needed later  ?)
      avgNoise = avgNoise + noiseVolts
      wait(500);
    }//for i
    avgNoise = avgNoise/20;
    noiseStart = true;
    Serial.print(avgNoise); Serial.println(" v.");

Looks like cattledog got there first !