Arduino outputting wrong variables

Hello.

The code I’m running is a simple read the adc and return the value over UART.
I’m currently experimenting with averaging the adc value.
And I’m constantly checking that i have a proper samplerate, by incrementing the variable for every read.

However when i print it out it returns what ever i have set the ampraw variable to +1.

So could you take a look at my code to see if I’m doing anything wrong.

I’ve tried it on a few Arduino WAN1300’s
that’s the one i’m running the code on.

Thanks.

int tid=millis();
int ampraw=0;
int amprawhigh=0;
int amprawlow=4096;
//int samples=0;
int avg=0;
const int avgsamplecount=3;
int avgsamples[3];
int samplerate=0;


// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  
  Serial.begin(115000);


  analogReference(AR_INTERNAL1V0);
  analogReadResolution(12);
  delay(1000);
  amprawlow=4096;
  amprawhigh=0;
  tid=millis(); 
  while ((millis()-tid)<10000) {
    //here i'm fixing the the ADC data so I can isolate the problem
    ampraw =  2; //analogRead(A0);
    if (ampraw<amprawlow) {
      amprawlow=ampraw;
    }
    if (ampraw>amprawhigh) {
      amprawhigh=ampraw;
    }
    for (int i=0;i<avgsamplecount;i++) {
      avgsamples[i]=avgsamples[i+1];
    }
    avgsamples[avgsamplecount]=ampraw;
    avg=0;
    for (int i=0;i<=avgsamplecount;i++) {
      avg=avg+avgsamples[i];
    }

    samplerate++;
    delayMicroseconds(100);
    //For somereason when i print the samplerate variable it returns the ampraw value +1.
    //I know this because if i change it the serial output changes.
    
    
    Serial.println(samplerate);
  }
 Serial.println(samplerate);

  
  

}

// the loop routine runs over and over again forever:
void loop() {

  
}

Check your accessed index in the array.

You are accessing elements that are not in your array.

Your code

    for (int i=0;i<avgsamplecount;i++) {
      avgsamples[i]=avgsamples[i+1];
    }

When i equals 2, your reading element with index 3 that does not belong to the array.

Your code

avgsamples[avgsamplecount]=ampraw;

You’re writing the element with index 3 which which is not an element of the array. Undefined behaviour can be the result.

Not said that fixing those will fix your problem.

Ah yes. Ofcourse.

Thank you so much for you help.